Follow a unidirectional data flow
Understanding the Flow of Data in a React Application
- Published on
3 min read
•
10 Best Practices for Writing Efficient and Maintainable React Applications
Table of Contents
Introduction
Data in React flows unidirectionally, which means that it passes through props from the parent component to the child components. This makes it simpler to comprehend how the application's data is managed and ensures that the child components are always in sync with the parent component's state.
Implementation
Here is an illustration of how data travels in a React application in a unidirectional pattern:
- The parent component wants to pass along some state to a child component.
- The state is provided as a prop to the child component by the parent component.
- After receiving the prop, the child component utilizes it to generate the necessary content.
- The updated state is passed as a prop to the child component whenever the parent component's state changes.
- After receiving the modified prop, the child component re-renders to reflect the altered state.
This design pattern makes it simpler to comprehend how the application's data is managed and helps to ensure that the child components are constantly in sync with the parent component's state.
Code Demo
import React, { useState } from 'react'
import ChildComponent from './ChildComponent'
const ParentComponent = () => {
const [name, setName] = useState('Umesh')
return (
<>
<ChildComponent name={name} />
<button onClick={() => setName('Arjun')}>Change Name</button>
</>
)
}
In this illustration, the ParentComponent
initializes the value of the state variable name
to "Umesh." The ChildComponent
is then given this state as a parameter with the name name. Here is an illustration of a ChildComponent
that gets the name prop
:
import React from 'react'
const ChildComponent = (props) => {
return <h1>Hello, {props.name}!</h1>
}
In this example, the ChildComponent
receives the name prop and uses it to render a greeting. If the name prop changes, the ChildComponent
will re-render to reflect the new value.
I hope this helps!
Happy Coding!