In React, data is passed between components in a unidirectional way. This means that the components must be composed in a way such that data is passed top-to-bottom — i.e. in one direction, from the parent component down to its children and so on. This way of unidirectional flow of data is an important part of creating React applications.
Since data only flows in one direction, you might wonder how a child component might update something in the parent. This is done by simply passing down props to the child component, which can be values or callback functions.
For example, the following shows how the parent component manages/owns the state, and passes down the relevant props to the child component in a unidirectional flow:
// Parent.jsx import React, { useState } from 'react'; import Child from './Child'; const Parent = () => { const [count, setCount] = useState(0); function handleButtonClick() { setCount(count + 1); } return ( <div> <h1>Parent</h1> <p>Count: {count}</p> <Child count={count} onButtonClick={handleButtonClick} /> </div> ); } export default Parent;
// Child.jsx import React from 'react'; const Child = (props) => ( <div> <h2>Child Component</h2> <p>Count: {props.count}</p> <button onClick={props.onButtonClick}> Click me </button> </div> ); export default Child;
In this example, the Parent
component manages the state and passes it down as a prop to the Child
component. The Child
component can then update the parent's state by invoking the callback function passed down to it as a prop. This way of passing data in one direction helps to simplify the flow of data and prevent unintended consequences or side effects.
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.