There are many cases in which you will need to change a parent component’s state from a child component. Very often you will have a state that needs to be accessed as well as mutated from many places in your app. This is actually a problem that is also solved by state management libraries such aS redux and the Context API, but the majority of the time, there is a simpler solution.
The simple solution is to pass the setState
function down to the child components, where they can call it as needed. This is demonstrated below.
import { useState } from 'react';
const ParentComponent = () => {
const [state, setState] = useState({data: 'important data'});
return <ChildComponent setState={setState} />;
};
const ChildComponent = ({ setState }) => {
const handleClick = () => setState({data: 'new important data'});
return <button onClick={handleClick}>Update Parent's State</button>;
};
Here, we pass the setState
function returned by useState
down to the child component, which uses it in an event handler to update its parent’s state.