Data Flow in React JS
React follows a unidirectional data flow, meaning that data flows in a single direction through the components. This helps in maintaining a predictable state and making it easier to understand how changes affect the application. In React we can pass props from Parent component to child and with the help of callback can also pass props from child to parent.
1. Parent to Child:
Data is passed from parent components to child components through props. The parent component owns the state, and it passes down relevant data to its child components as props.
Props (short for “properties”) in React are a mechanism for passing data from a parent component to its child component as a set of read-only attributes.
For example: Sending the data from parent to child as “Hello, this is data from the parent to child”.
Javascript
// Parent component import React, { useState } from 'react' ; import ChildComponent from './ChildComponent' ; function ParentComponent() { const [data, setData] = useState( '"Hello, this is the data from the parent to child".!' ); // passing the data to child as props return <ChildComponent data={data} />; } export default ParentComponent; |
Javascript
// Child component import React from 'react' ; // the child is receiving the data as props function ChildComponent(props) { return <p>{props.data}</p>; } export default ChildComponent; |
Output:
2. Child to Parent:
To communicate from child to parent, the parent can pass down a callback function as a prop to the child. The child can then invoke this function to send data back to the parent.
Example: Sending the data from child to parent as “Hello, this is data from the child to parent”.
Javascript
// Parent component import React, { useState } from "react" ; import ChildComponent from "./ChildComponent" ; function ParentComponent() { const [dataFromChild, setDataFromChild] = useState( "" ); const handleDataFromChild = (data) => { setDataFromChild(data); }; return ( <div> <p>Data from child: {dataFromChild}</p> <ChildComponent sendDataToParent={handleDataFromChild} /> </div> ); } export default ParentComponent; |
Javascript
// Child component import React from "react" ; function ChildComponent(props) { const sendData = () => { props.sendDataToParent( "Hello from child!" ); }; return <button onClick={sendData}>Send Data to Parent</button>; } export default ChildComponent; |
Output:
Understanding React State and Data Flow
React, a very popular JavaScript library used for building user interfaces has the concept of components and they can manage the states efficiently. ReactJs is based on the concept of uni-directional data transfer. In this article, we will understand React State and Data Flow across the application.