State & Events
React Lifting State Up
Lifting state up means moving a piece of state from a child to the closest common ancestor of the components that need it, then passing the value down as a prop and an updater function down as a callback.
What is Lifting State Up in React?
Lifting state up means moving a piece of state from a child to the closest common ancestor of the components that need it, then passing the value down as a prop and an updater function down as a callback.
Why Lifting State Up matters
Two sibling components cannot see each other’s state. Whenever a filter must affect a list, or a tab must control a panel, the shared value has to live above both.
Lifting State Up example
function InternshipSearch() {
const [city, setCity] = useState('All');
return (
<>
<CityFilter value={city} onChange={setCity} />
<JobResults city={city} />
</>
);
}
function CityFilter({ value, onChange }) {
return (
<select value={value} onChange={e => onChange(e.target.value)}>
<option>All</option><option>Pune</option><option>Bengaluru</option>
</select>
);
}How this works
CityFilter is now fully controlled: it renders whatever value it is given and reports changes upward. It holds no state of its own, which makes it reusable and easy to test.
Key points to remember
- Find the closest common parent of everything that reads the value.
- Pass the value down as a prop, the setter down as a callback.
- When the chain gets long, switch to context rather than threading through five layers.
Common mistakes with Lifting State Up
- Duplicating the value in both parent and child, creating two sources of truth.
- Lifting state all the way to the app root when a nearer parent would do, causing wide re-renders.
React Lifting State Up— Interview Questions & FAQs
How do two sibling components share state?+
They cannot directly. Move the state into their nearest common parent and pass the value and an updater down as props — the pattern called lifting state up.
