Lesson 9 of 37State
Lifting State Up
Share state between components by moving it to their closest common parent and passing it down as props.
Sooner or later two components need the same data: a search box and the results list, a cart icon and the product page, two accordion panels where opening one closes the other. Because state is private to each component, they cannot reach into each other. The fix, lifting state up, is the single most important pattern for structuring React apps, and interviewers use it to judge whether you can design components, not just write them.
The problem: siblings cannot share
Here is an FAQ where each panel keeps its own isOpen state. The requirement is "only one answer open at a time". Try opening both.
Both open, and there is no way to fix it inside Panel: the first panel cannot see or change the second panel's state.
The fix in three steps
To coordinate siblings, move the state to their closest common parent and pass it down.
- Remove the state from the children.
- Pass what they need as props from the parent: here,
isOpen. - Add an event prop so children can ask the parent to change it: here,
onShow.
Now App holds one number, openIndex, and each panel's isOpen is derived from it. Two panels can never both be open, because the data cannot express that.
Order the steps to lift state from two siblings into their parent.
- Tap the steps below in the right order.
Where state lives, what re-renders
When the state changes, React re-renders the component that owns it and, by default, every component below it. Lifting state therefore has a cost: the higher you put it, the more re-renders. That is usually fine (rendering is fast), but it is a reason not to lift state higher than needed.
SearchBox and Results both need query. Their closest common parent is SearchPage, so the state lives there (pink).
Sidebar shows the selected folder, and MessageList shows that folder's messages. Both are children of Mailbox, which is a child of App. Where should selectedFolder live?Controlled and uncontrolled components
After lifting, Panel has no state of its own. Its behaviour is fully decided by props. A component like that is called controlled: the parent controls it. The first version, with its own isOpen, was uncontrolled: the parent could not influence it.
| Uncontrolled | Controlled | |
|---|---|---|
| Who owns the state | The component itself | Its parent, via props |
| Parent can read or change it | No | Yes |
| Setup | Less code, drop it in | Parent must pass value and onChange |
| Example | <input defaultValue="hi" /> | <input value={text} onChange={...} /> |
You will see the same words with form inputs in the next lesson. The idea is identical: is the value driven by React state through props, or kept internally?
A single source of truth
For each piece of data, exactly one component should own it as state. Everything else receives it as props or computes it. This is the single source of truth principle.
A common mistake is copying a prop into state:
function Greeting({ name }: { name: string }) {
// Bug: only uses `name` on the first render. If the parent's name changes, this stays stale.
const [displayName, setDisplayName] = useState(name);
return <h2>Hello, {displayName}</h2>;
}
function GreetingFixed({ name }: { name: string }) {
return <h2>Hello, {name}</h2>; // just use the prop
}<Greeting name={name} /> (the buggy version) with name set to Ada, then later changes name to Sam. What does the heading show?Here is the search example wired properly. query lives in the parent; the input is controlled; the results are derived during render, never stored.
Deriving instead of syncing state
Once state lives in the right place, the next mistake is storing things you could compute. Ask of every piece of state: can I calculate this from props or other state? If yes, it is not state. Calculate it during render.
You will meet useEffect later in the course. A very common misuse of it is to "keep two pieces of state in sync":
// Avoid: hits is a copy of something you can compute
const [query, setQuery] = useState("");
const [hits, setHits] = useState(PRODUCTS);
useEffect(() => {
setHits(PRODUCTS.filter((p) => p.includes(query)));
}, [query]);
// Better: derive it. No extra state, no extra render, never out of date
const [query, setQuery] = useState("");
const hits = PRODUCTS.filter((p) => p.includes(query));The effect version renders twice for every keystroke: once with the new query and the old hits, then again after the effect runs. For a moment the screen is wrong, and on a slow device users see it. If the calculation is genuinely expensive, wrap it in useMemo (the performance lesson covers when that helps). It is still derived; you are just caching it.
The most valuable form of this rule: store ids, not copies. Here is a recipe planner. Select Pasta, then click "+1 serving" on Pasta in the list. Do it in both versions.
In the first planner the list says 3 servings and the detail line still says 2. selected is a second copy of the Pasta object, and updating the list made a new Pasta object that the copy knows nothing about. Two sources of truth, and they drifted. Storing only selectedId and looking the item up during render means there is one Pasta, so it can never be stale. The same applies to "the selected rows" (store a set of ids), "the item being edited" and "the current user's cart line".
Resetting state with key
Earlier you saw why copying a prop into state is a bug: useState(name) only reads name on the first render. Sometimes, though, a copy is exactly what you want. An edit form needs a draft that starts from the saved contact, changes as you type, and only touches the real data when you press Save. That draft is state, and its starting value comes from a prop.
The problem appears when the prop changes to a different contact. The form component stays mounted, so its draft still holds the previous contact's name. The fix is not to sync it with an effect. It is to tell React that a different contact means a different form, with a key:
Edit Ada's name without saving, then click Sam: the field shows Sam, because key={selected.id} gave Sam his own fresh EditContact. Remove the key in your head and the field would keep showing your half-typed Ada draft while the Save button wrote it onto Sam.
You have four options when state must follow a prop, in rough order of preference:
- Do not store it. If the component does not need its own draft, read the prop directly.
- Reset with a key, as above, when a new value of the prop means "start over".
- Lift the draft up and make the form controlled, when the parent needs to know about it. An "unsaved changes" warning on navigation is a good reason.
- Adjust during render: keep the previous prop in state and, if it changed, call the setter during render. React supports this, but it is hard to read, so use it only when you must keep part of the state, such as resetting a selection while keeping a scroll position.
What you should not do is reset state in an effect. The component first renders with the stale draft, the effect fires, and it renders again, so users briefly see the wrong data, and every extra effect is one more thing to keep correct.
CommentBox keeps its text in useState and is rendered as <CommentBox postId={post.id} />. Switching posts keeps the half-written comment from the previous post. What is the simplest correct fix?Match each situation to the right move.
When lifting goes too far
Lifting is the right first move, but apply it over and over and you get a familiar mess: one component near the top owns twenty pieces of state, and props travel through four layers that never use them just to reach the one that does. That is prop drilling. Every layer in the middle has to change when the data changes shape, and every keystroke re-renders everything under the owner.
The fix is not always "lift higher" or "add a library". Work up this ladder and stop at the first step that solves the problem.
Colocate first. State that only one component uses should live in it. Moving state back down is as useful as lifting it up, and it shrinks re-renders.
Composition is the step most developers skip. Here App owns user, but only UserMenu, three levels down, needs it:
// Drilling: Layout and Sidebar accept `user` only to pass it on
<Layout user={user} />
function Layout({ user }) { return <Sidebar user={user} />; }
function Sidebar({ user }) { return <nav><UserMenu user={user} /></nav>; }
// Composition: App builds UserMenu itself; the middle layers just place it
<Layout sidebar={<Sidebar menu={<UserMenu user={user} />} />} />
function Layout({ sidebar }) { return <div className="layout">{sidebar}</div>; }
function Sidebar({ menu }) { return <nav>{menu}</nav>; }Layout and Sidebar no longer know a user exists. Add a field to the user and only App and UserMenu change. This is the slots idea from the components lesson, applied to data flow.
Signs you have lifted too far: a prop name repeated in four files in a row, a top-level component with a dozen useState calls for unrelated features, or a profiler showing the whole page re-rendering on each keystroke in one input. The context lesson is next on the ladder, and the state management at scale lesson covers stores, URL state and server caches in depth.
Match each piece of state to where it should live.
One-at-a-time accordion
Each Panel keeps its own isOpen state, so several can be open at once. Lift the state up into App so that at most one panel is open.
- All panels start closed.
- Clicking a panel's title button opens it and closes any other.
- Clicking the title of the panel that is already open closes it.
- An open panel shows its text in a
<p className="answer">.
Panel should receive isOpen and an onToggle callback as props instead of owning state.
Synced temperature inputs
Two inputs, Celsius and Fahrenheit, should always agree. Typing in either one updates the other.
- Both are
<input type="text">witharia-label="Celsius"andaria-label="Fahrenheit". F = C × 9 / 5 + 32andC = (F − 32) × 5 / 9.- Round the converted value to at most one decimal place and show it without trailing zeros (
212, not212.0;37.8, not37.77).String(Math.round(x * 10) / 10)does this. - If the typed text is empty or not a number, the other input is empty.
Hint: store one piece of state, the text the user typed and which scale it was in, and derive the other input during render.
- lifting state up
- Moving state to the closest common parent of the components that need it, then passing it down as props.
- controlled component
- A component whose important values come from props, so its parent controls it.
- uncontrolled component
- A component that keeps its own internal state that the parent cannot drive.
- single source of truth
- Each piece of data is owned as state by exactly one component; everything else reads or derives it.
- derived state
- A value computed during render from props or state, instead of being stored separately.
- prop drilling
- Passing a prop through several components that do not use it, only to reach one that does.
- colocation
- Keeping state in the component that uses it, as low in the tree as possible.
- key reset
- Changing a component's
keyso React mounts a fresh instance with fresh state.