How to lift state up in React
· Category: React
Short answer
Lifting state up means moving shared state from child components to their closest common parent, which then passes the state and callbacks down as props.
Steps
- Identify components that need the same changing data.
- Move the state to their closest common ancestor.
- Pass the current state down as props.
- Pass callback functions down so children can request state changes.
Example
function Parent() {
const [celsius, setCelsius] = useState(0);
return (
<>
<TemperatureInput scale="c" value={celsius} onChange={setCelsius} />
<TemperatureInput scale="f" value={toF(celsius)} onChange={(f) => setCelsius(toC(f))} />
</>
);
}
function TemperatureInput({ scale, value, onChange }) {
return (
<input
value={value}
onChange={(e) => onChange(Number(e.target.value))}
/>
);
}
Tips
- Only lift state that is genuinely shared. Local state should stay local.
- If many components need the same state, consider Context or a dedicated state management library.