How to Propagate State Updates from Child to Parent in React Without Redux
React's unidirectional data flow model often presents challenges in updating parent components' state from their descendants. Let's consider a scenario where the following component structure exists:
Component 1 - Component 2 - Component 4 - Component 5 Component 3
The goal is for Component 3 to display data based on Component 5's state. Since props are immutable, passing state from Component 5 to Component 1 is not feasible.
Instead, React provides a solution through child-parent communication using callback functions. The following code snippet demonstrates how this can be achieved:
class Parent extends React.Component { constructor(props) { super(props); this.handler = this.handler.bind(this); } handler() { this.setState({ someVar: 'some value' }); } render() { return <Child handler={this.handler} />; } } class Child extends React.Component { render() { return <Button onClick={this.props.handler} />; } }
In this example, the parent passes a callback function, handler(), to the child component via props. This function, when invoked by the child, triggers a state update in the parent component, allowing the state change to propagate up the component tree.
While this approach addresses the immediate challenge, it may require rethinking the component structure. In the given scenario, Components 5 and 3 don't appear to have a direct relationship. To alleviate this issue, considering wrapping them within a higher-level component that manages the state for both components and propagates it through props. This allows for a more modular and maintainable solution.
The above is the detailed content of How to Update Parent Component State from a Deeply Nested Child Component in React?. For more information, please follow other related articles on the PHP Chinese website!