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
Parent
component, we use theuseState
hook to create a state variable calledheader
and its corresponding setter function,setHeader
. The initial value ofheader
is set to "I am a Parent". - The
Parent
component renders theChild
component and passes a callback functionhandleClick
as a prop. - In the
Child
component, we have a button with anonClick
event that invokes thehandleClick
function passed from the parent. When the button is clicked, it triggers the callback function and passes the newheader
value as an argument. - Inside the callback function in the
Parent
component, we update the state by callingsetHeader
with the newheader
value. - The updated state causes a re-render, and the new
header
value 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:
Top comments (0)