In React, data typically flows down from parent to child components through props. However, there may be scenarios where we need to update the parent component when changes occur in the child component. In this tutorial, we'll explore inverse data flow in React and learn how to update the parent component by using callback functions. We'll build a simple example where a button click in the child component updates the state and changes the heading in the parent component.
Setting up the Components:
We'll create two components: Parent and Child. The Parent component will render the Child component and display a heading. The Child component will have a button that triggers the state update in the parent component.
Parent.js
import React, { useState } from 'react';
import Child from './Child';
const Parent = () => {
const [header, setHeader] = useState('I am a Parent');
return (
<div className="parent">
<h1>{header}</h1>
<Child handleClick={(newHeader) => setHeader(newHeader)} />
</div>
);
}
export default Parent;
Child.js
import React from 'react';
const Child = (props) => {
return (
<div className="child">
<h1>I am a Child</h1>
<button onClick={() => props.handleClick("I am a Changed Parent")}>Click</button>
</div>
);
}
export default Child;
Explanation:
- In the
Parentcomponent, we use theuseStatehook to create a state variable calledheaderand its corresponding setter function,setHeader. The initial value ofheaderis set to "I am a Parent". - The
Parentcomponent renders theChildcomponent and passes a callback functionhandleClickas a prop. - In the
Childcomponent, we have a button with anonClickevent that invokes thehandleClickfunction passed from the parent. When the button is clicked, it triggers the callback function and passes the newheadervalue as an argument. - Inside the callback function in the
Parentcomponent, we update the state by callingsetHeaderwith the newheadervalue. - The updated state causes a re-render, and the new
headervalue is displayed in the parent component.
Inverse data flow in React allows us to update the parent component when changes occur in the child component. By passing callback functions as props from the parent to the child, we can modify the state in the parent component based on child interactions. This approach allows for better separation of concerns and modularization of components, as the child component doesn't directly modify the parent's state but instead notifies the parent to handle the state update. Understanding this concept is essential for managing data and state across different components in a React application.
Happy Coding!
Resources:

Latest comments (0)