Sub topic 14
Lifting State Up to Share It
This chapter assumes you know function components, props, destructuring, and the basics of useState, including how to update objects and arrays without mutating them. It covers what to do when two components need to show or change the same piece of data.
The problem: two components, one value
Each call to useState creates state that belongs to one component instance. A sibling cannot read it, and a child cannot change it unless the owner passes something down. That isolation is usually what you want. It becomes a problem when two components must agree.
Suppose a page has two panels, and opening one should close the other. If each panel keeps its own isOpen state, neither knows what the other is doing. They can both end up open, and no code in either panel can fix that.
The fix is to move the state out of the children and into their closest common parent. This is called lifting state up. The parent owns the value and passes it down through props. The children report user actions back through callback props.
The pattern in three steps
- Remove the state from the child components. They become controlled by props.
- Declare the state in the closest common parent of the components that need it.
- Pass the value down as a prop, and pass down a function that asks the parent to change it.
Here is the accordion from the plan. Panel has no state of its own. It receives isActive and onShow.
import { useState } from 'react';
function Panel({ title, isActive, onShow, children }) {
return (
<section>
<h3>{title}</h3>
{isActive ? <p>{children}</p> : <button onClick={onShow}>Show</button>}
</section>
);
}
function Accordion() {
const [activeIndex, setActiveIndex] = useState(0);
return (
<>
<Panel title="About" isActive={activeIndex === 0} onShow={() => setActiveIndex(0)}>
About text
</Panel>
<Panel title="Details" isActive={activeShow={() => setActiveIndex(1)}>
Details text
</Panel>
</>
);
}activeIndex is a single number, one panel can match it. The "only one open at a time" rule holds by construction. There is no second flag that could disagree with the first.
How data and events move
Data flows down through props. Events flow up through callbacks. The parent never reaches into a child, and the child never writes to the parent's state directly. It calls a function it was given.
This is why the pattern is sometimes called one-way data flow. You can always answer "where does this value come from?" by looking up the tree until you find the component that calls useState.
A second example: a shared filter
Lifting is not only for toggles. Here a search box and a results list need the same query. The query lives in the parent. The input is a controlled input, so it only displays the value it receives and reports changes.
import { useState } from 'react';
function SearchBox({ query, onQueryChange }) {
return (
<input
value={query}
onChange={e => onQueryChange(e.target.value)}
placeholder="Search fruit"
/>
);
}
function Results({ items, query }) {
const visible = items.filter(item =>
item.toLowerCase().includes(query.toLowerCase())
);
return (
<>
<p>{visible.length} of {items.length} match</p>
<ul>
{visible.map(item => <li key={item}>{item}</li>)}
</ul>
</>
);
}
function FruitSearch() {
const [query, setQuery] = useState('');
const fruit = ['Apple', 'Apricot', 'Banana', 'Cherry'];
return (
<>
<SearchBox query={query} onQueryChange={setQuery} />
<Results items={fruit} query={query} />
</>
);
}Two details are worth noting. First, setQuery is passed directly as onQueryChange. A state setter is an ordinary function, so this works when the child calls it with the new value. Second, Results computes visible during render from items and query. Lifting one value is enough. You do not need to store a filtered list as extra state, which matches the earlier rule about deriving values.
Choosing where the state lives
Put the state in the closest common parent of every component that reads or writes it. Going higher than necessary is allowed but has costs.
| Placement | Effect |
|---|---|
| In one component only | Simple and isolated. Nothing else can read it. |
| In the closest common parent | Shared by exactly the components that need it. |
| Higher than needed | More components re-render on each change, and more props must pass through intermediate components. |
A useful test is to ask who needs to read the value and who needs to change it. If only one component does both, keep the state there. If several do, find their nearest shared ancestor.
You can also lift in stages. Start with state local to a component. When a sibling later needs it, move it up one level. Avoid lifting speculatively, because moved state makes components less self-contained.
Controlled and uncontrolled components
A component is controlled when its important information comes from props and it changes only by calling callbacks. Panel above is controlled, and so is SearchBox. A component is uncontrolled when it keeps that information in its own state.
Uncontrolled components are easier to use in isolation. Controlled components are more flexible because the parent can coordinate them. Many real components support both: they use local state by default and accept an optional prop to take over. Lifting state up is the act of turning an uncontrolled component into a controlled one.
Edge cases and gotchas
Props are not state
A child that copies a prop into its own state with useState(props.value) uses the prop only on the first render. Later changes to the prop are ignored, so the child and parent drift apart. If the parent owns the value, the child should read the prop directly. If you need to reset the copy when something changes, give the child a key, as covered in the chapter on state identity.
Updating the parent from a child during render
Calling onShow() or a setter while rendering is a bug. Callbacks belong in event handlers. Write onClick={() => onShow()} or onClick={onShow}, not onClick={onShow()}, which calls the function immediately on every render and can trigger an infinite loop.
Passing arguments through callbacks
When the parent needs to know which child fired, either bind the identity in the parent, as onShow={() => setActiveIndex(1)} does, or have the child pass it back.
function Row({ id, label, onSelect }) {
return <li onClick={() => onSelect(id)}>{label}</li>;
}Prop drilling
Lifting can push a value through several layers of components that do not use it, only to reach a deep descendant. This is called prop drilling. Before reaching for a new tool, try restructuring. Passing the deep component as children often removes the middle layers' need to know about the value. If drilling is still painful, context is the usual next step, which is outside this chapter.
Shared state that is really an object or list
If lifted state is a list and children edit items, the parent should expose focused callbacks such as onToggle(id) and onRemove(id). The children do not mutate the array they receive. All changes still go through the parent's setter, using map, filter, and spread as before.
One source of truth
Each piece of data should have exactly one owner. If two components each hold a copy and you try to synchronize them with extra code, you will eventually create an inconsistent state. Lifting is the way to restore a single source of truth.
Summary of when to lift
- Two or more components must show or change the same data.
- One component's change must affect a sibling or a relative elsewhere in the tree.
- You find yourself writing code to keep two state variables synchronized.
Exercise
In the Accordion, a teammate adds a local useState(false) called open inside each Panel and toggles it on click, while keeping activeIndex in the parent. What goes wrong, and how do you fix it?
Show answer
Each Panel now has two sources of truth: its own open and the parent's isActive. Clicking Show in one panel sets only that panel's open, so the parent's activeIndex does not change and the other panel does not close. Several panels can be open at once. Remove the local state and render from the isActive prop alone, calling onShow to ask the parent to change activeIndex.
Exercise
What is wrong with <button onClick={onShow(1)}>Show</button>, and what are two correct ways to write it?
Show answer
onShow(1) runs during render and passes its return value to onClick. If it sets state, this triggers another render and can loop forever. Write onClick={() => onShow(1)} to call it on click, or have the child receive an id prop and call onShow(id) inside an arrow function handler.
Exercise
A parent holds const [query, setQuery] = useState(''). A child Results does const [q, setQ] = useState(props.query) and filters by q. Typing in the parent's input does not change the results. Why, and what is the fix?
Show answer
useState uses its argument only on the first render, so q keeps its initial value while the query prop changes. Delete the child's state and filter by props.query directly.