Lifting State Up
When multiple components need to share the same changing data, the common React pattern is to move ('lift') that state up to their closest common ancestor, and pass it down via props.
This keeps a single source of truth and avoids components getting out of sync with duplicated state.
The pattern
Instead of each sibling component holding its own copy of state, the parent holds the state and passes both the value and an updater function down as props.
Why it matters
Lifting state up prevents inconsistent UI where two components show different values for what should be the same piece of data.
function Parent() {
const [temp, setTemp] = useState(20);
return (
<div>
<Display temp={temp} />
<Slider temp={temp} onChange={setTemp} />
</div>
);
}
function Display({ temp }) {
return <p>{temp}ยฐC</p>;
}
function Slider({ temp, onChange }) {
return (
<input type="range" value={temp} onChange={e => onChange(Number(e.target.value))} />
);
}20ยฐC (Display updates as the slider moves)Parent owns temp state; Display and Slider stay in sync through it.
Key points
- Lifting state up moves shared state to the closest common ancestor.
- Child components receive both the value and an updater via props.
- This keeps a single source of truth for shared data.
- It avoids inconsistent UI between sibling components.
