Sub topic 6
Lifting State to the Closest Common Parent
This chapter covers the technique itself: how to find the component that should own shared state, and how to move the state there. It assumes you can write function components in JSX and pass props. It also assumes you know useState, destructuring and arrow functions, and how to handle events such as onChange. You should also be comfortable with the idea that data flows down through props and requests for change flow up through callbacks.
The problem in one picture
Two components that each call useState get two separate values. React stores state per component instance, so nothing connects them.
import { useState } from 'react';
function Field({ label }) {
const [text, setText] = useState('');
return (
<label>
{label}: <input value={text} onChange={e => setText(e.target.value)} />
</label>
);
}
export default function App() {
return (
<>
<Field label="First" />
<Field label="Second" />
</>
);
}Typing in "First" leaves "Second" empty. Each Field has its own text. A component cannot read its sibling's state, and props only travel from parent to child. The only place that can see both children is their parent.
The working model
Lifting state up is a mechanical refactor with four steps:
- Identify every component that reads or changes the shared value.
- Find their closest common parent, the lowest component in the tree that contains all of them.
- Move the
useStatecall into that parent. - Pass the value down as a prop, and pass a callback down so children can request changes.
After the move, the children have no state of their own for that value. They render what they are given and report user input upward. This keeps a single source of truth: one variable holds the value, and every other component displays it.
Worked example: lifting the text
Here is the same app after the refactor.
import { useState } from 'react';
function Field({ label, value, onChange }) {
return (
<label>
{label}: <input value={value} onChange={e => onChange(e.target.value)} />
</label>
);
}
export default function App() {
const [text, setText] = useState('');
return (
<>
<Field label="First" value={text} onChange={setText} />
<Field label="Second" value={text} onChange={setText} />
</>
);
}Three things changed:
useStatemoved fromFieldtoApp.Fieldnow takesvalueandonChangeas props. It has no hooks.Apppasses the sametextand the samesetTextto both children.
onChange={setText} works because Field calls onChange(e.target.value) with the new string, and setText accepts a string. The child does not know or care that the callback is a state setter. It only knows it should call the function when the user types.
What happens when you type
Data goes up as an event and comes back down as props. Neither child ever updates the other directly. This is why the pattern scales: you can reason about each component from its props alone.
Why the closest common parent
You could put the state in any ancestor of both children, but the closest one is usually right.
- Too low and a component that needs the value cannot reach it. State in
Fieldis invisible to its sibling. - Too high and every update re-renders a larger subtree than necessary. You also pass props through components that do not use them, and unrelated code can start depending on state it should not know about.
To find the owner, look at the component tree and ask which components need the value. Then walk upward until one component contains them all. That component owns the state.
A rule instead of a value: the accordion
State does not have to be the data itself. Sometimes it encodes a rule that spans siblings. In an accordion, only one panel may be open. No single panel can enforce that, because each would need to know what the others are doing.
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>
);
}
export default function Accordion() {
const [activeIndex, setActiveIndex] = useState(0);
return (
<>
<Panel
title="About"
isActive={activeIndex === 0}
onShow={() => setActiveIndex(0)}
>
Text about the project.
</Panel>
<Panel
title="Details"
isActive={activeIndex === 1}
onShow={() => setActiveIndex(1)}
>
More details here.
</Panel>
</>
);
}Accordion stores one number, activeIndex. Each panel gets a boolean computed from it, and a callback that sets the index. Opening one panel automatically closes the other, because only one index can be stored. The invalid state "both open" cannot be represented.
Compare this with the alternative of one isOpen boolean per panel. Keeping them consistent would require extra code, and bugs would be easy to introduce.
Lifting changes who is in charge
After lifting, the children are controlled by the parent. They are "dumb" in the sense that they hold no state for that value. This has a practical consequence: the parent can do more than mirror the value. It can validate, transform, or reject an update before storing it.
function App() {
const [text, setText] = useState('');
function handleChange(next) {
setText(next.slice(0, 20));
}
// ...
}Both inputs now enforce a 20-character limit with no change to Field. This is the benefit of having one place where the value is written.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Child input is stuck and typing does nothing | `value` is passed but `onChange` is missing or not called | Pass a callback and call it with the new value |
| Child shows the first value but never updates | Child copies the prop into its own state with `useState(value)` | Remove the child's state and read the prop directly |
| Handler runs on every render, or "too many re-renders" | `onShow={setActiveIndex(0)}` calls the setter during render | Pass a function: `onShow={() => setActiveIndex(0)}` |
| Warning about switching from uncontrolled to controlled | `value` is `undefined` on the first render | Initialize state with `''` or another defined value |
| Values drift apart again | The same data is stored in both parent and child | Keep one copy and derive the rest |
Copying a prop into state
This is the most common mistake after lifting.
function Field({ label, value, onChange }) {
const [text, setText] = useState(value); // bug: copy made once
return (
<label>
{label}: <input value={text} onChange={e => setText(e.target.value)} />
</label>
);
}useState(value) uses value only on the first render. Later changes to the prop are ignored, and you are back to two copies of the truth. The child should render value and call onChange, nothing else.
Passing the wrong thing to the callback
Your callback's parameter has to match what the child sends. If Field calls onChange(e.target.value) but the parent expects an event, setText receives a string where code reads e.target.value from it and gets undefined. Decide whether children pass raw values or events, and keep that consistent. Passing raw values, as in this chapter, keeps parents independent of the DOM.
When not to lift
Lift only when two or more components need the same value at the same time. If one component alone uses a piece of state, leave it there. Over-lifting makes the parent noisy, causes extra re-renders, and forces props through the tree. Later chapters cover pushing state back down, passing it through many layers, and alternatives such as context. For now the test is simple: who needs this value, and what is the lowest component that contains them all?
Exercise
In the first example, a Field component keeps its own text state. Describe the two code changes needed so that both Field components always show the same text, and say which component should hold the state.
Show answer
Move const [text, setText] = useState('') out of Field and into App, the closest common parent of both fields. Then change Field to take value and onChange props, use value={value} on the input, call onChange(e.target.value) in its handler, and have App pass text and setText to both fields.
Exercise
A teammate writes <Panel onShow={setActiveIndex(1)} /> and the app crashes with "Too many re-renders". Why, and what is the fix?
Show answer
setActiveIndex(1) is called immediately while Accordion renders, not when the button is clicked. That update triggers another render, which calls it again, in a loop. Pass a function instead: onShow={() => setActiveIndex(1)}.
Exercise
A Field receives value as a prop but also declares const [text, setText] = useState(value) and renders text. The parent changes value and the input does not change. Explain why.
Show answer
useState(value) reads the prop only on the first render, so the child's text is a separate copy that never follows later prop changes. Delete the child's state and render value directly.