Languages
[Edit]
EN

React - update parent's state

0 points
Created by:
Savannah
559

In this article, we would like to show you how to update parent's state in React.

Below we create two React components:

  • Parent - which has a state created with useState hook, managed with updateState function,
  • Child - which renders a button element that calls Parent's updateState method on click event.

Inside Parent, we render the Child component to which we pass updateState function as a handler property.

Child component receives handler via props and uses props.handler inside onClick property to update Parent's state when the onClick event occurs.

Runnable example:

// ONLINE-RUNNER:browser;

// Note: Uncomment import lines while working with JSX Compiler.
// import React from 'react';
   
const Parent = () => {
  const [state, setState] = React.useState(0);

  const updateState = () => {
    setState((state) => state + 1);
  };
  return (
    <div>
      <div>Parent's state: {state}</div>
      <Child handler={updateState} />
    </div>
  );
};

const Child = (props) => {
  return (
    <div>
      <button onClick={props.handler}>Update</button>
    </div>
  );
};

const root = document.querySelector('#root');
ReactDOM.render(<Parent />, root );

Alternative titles

  1. React - change parent's state
  2. React - update parent's state from child
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

ReactJS

React - update parent's state from child
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join