In React, βlifting state upβ means moving shared state to the nearest common parent component.
This allows sibling components to access and update the same state.
Sometimes, two or more components need to share the same data.
Instead of duplicating state, we lift it up to their common ancestor, so:
Letβs say two components need to keep the same value in sync.
function Parent() {
const [text, setText] = useState('');
return (
<>
<InputBox value={text} onChange={setText} />
<Preview text={text} />
</>
);
}
function InputBox({ value, onChange }) {
return (
<input
type="text"
value={value}
onChange={(e) => onChange(e.target.value)}
/>
);
}
function Preview({ text }) {
return <p>You typed: {text}</p>;
}
π
InputBox
updates the value, andPreview
reflects it β both connected through the parent.
Step | Description |
---|---|
1οΈβ£ | Create state in the common parent |
2οΈβ£ | Pass the value + setter down as props |
3οΈβ£ | Children read or update via those props |
function App() {
const [count, setCount] = useState(0);
return (
<>
<Counter label="Counter A" count={count} setCount={setCount} />
<Counter label="Counter B" count={count} setCount={setCount} />
</>
);
}
function Counter({ label, count, setCount }) {
return (
<div>
<h3>
{label}: {count}
</h3>
<button onClick={() => setCount(count + 1)}>+1</button>
</div>
);
}
β Both components share the same count β Updating one updates both
β Do This | π« Avoid This |
---|---|
Keep shared state in the parent | Duplicate state in children |
Pass handlers as props | Try to sync with useEffect() |
Keep child components stateless | Let both child and parent manage the same state |
Concept | Description |
---|---|
Lifting state | Move shared state to the nearest common parent |
Props | Pass value + setters to children via props |
Sync logic | Ensures consistency across related components |
Simpler data flow | Keeps data flow top-down and easier to manage |