Lifting State Up in React
✅ What is “Lifting State Up”?
When two or more sibling components need to share the same state, you should move the state up to their common parent component.
This is called “lifting state up”.
🧠 Why Lift State?
Let’s say you have:
- A
<Form />
component to input data - A
<Preview />
component to display that data
They are siblings, but both need access to the same data.
So:
📌 You lift the state to their parent component, then pass data/functions via props.
✅ Example: Shared Input and Preview
App.js
import React, { useState } from 'react';
import Form from './Form';
import Preview from './Preview';
function App() {
const [name, setName] = useState("");
return (
<div>
<h1>Lifting State Up Example</h1>
<Form name={name} setName={setName} />
<Preview name={name} />
</div>
);
}
export default App;
Form.js
function Form({ name, setName }) {
return (
<div>
<label>Enter name: </label>
<input
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Type name"
/>
</div>
);
}
export default Form;
Preview.js
function Preview({ name }) {
return (
<div>
<h3>Preview: {name}</h3>
</div>
);
}
export default Preview;
✅ When to Lift State?
Lift state when:
- Two or more components need to read or update the same data
- You want data flow to stay clear and predictable
✅ Want to Try It?
Build an app with:
- A
<ColorPicker />
component to select a color - A
<Box />
component that displays that color
Use lifting state up so both use the same color state.
Keep Learning 🙂