What is Lifting State Up?
Lifting State Up is a React concept where the state is moved from a child component to their common parent component so that multiple child components can share and use the same state.
When two or more child components need to use the same data, move the state to their nearest common parent.
Why Do We Lift State?
Normally, data flows from parent to child using props.
But sometimes two child components need to access or update the same data.
For example:
App
/ \
Input Display
Suppose Input changes a value and Display needs to show that value.
If the state is inside Input, Display cannot directly access it.
So, we move the state to the parent:
App
state
/ \
↓ ↓
Input Display
Now both child components can communicate through the parent.
Example
Suppose we want to enter a name in one component and display it in another component.
Parent Component
import { useState } from "react";
function App() {
const [name, setName] = useState("");
return (
<div>
<InputBox name={name} setName={setName} />
<Display name={name} />
</div>
);
}
export default App;
Here, the state:
const [name, setName] = useState("");
is stored in the parent component App.
Child Component 1 – InputBox
function InputBox({ name, setName }) {
return (
<input
value={name}
onChange={(e) => setName(e.target.value)}
/>
);
}
The InputBox receives:
name
setName
through props.
When the user types something, setName() updates the state in the parent.
Child Component 2 – Display
function Display({ name }) {
return (
<h2>Hello {name}</h2>
);
}
The Display component receives the updated name through props and displays it.
How Does It Work?
The flow of data is:
App
name + setName
/ \
↓ ↓
InputBox Display
|
↓
setName()
|
↓
App state updates
|
↓
App re-renders
|
↓
Updated name
↓
Display
The important point is that the state belongs to the parent, while the child components receive the state and setter function through props.
Lifting State Up vs Props
Props are the method used to pass the state and setter function from the parent to the child.
Lifting State Up
↓
Move state to common parent
↓
Pass state using props
↓
Child components share the data
Conclusion
Lifting State Up is a technique used to share state between sibling components. The state is moved to their nearest common parent, and the parent passes the state and setter function to the children through props. This keeps data flow predictable and makes components easier to manage.
Top comments (0)