Sub topic 2
Lifting state up and its limits
This chapter assumes you can write function components, use useState, pass functions as props, and read basic ES module syntax. It covers how to share state between sibling components by moving it to their closest common parent. It also covers the points where that approach starts to hurt, which is why the later patterns in this tutorial exist.
The problem: siblings cannot see each other's state
State in React belongs to the component that calls useState. Data flows down through props, so a component can only read state that it owns or that a parent passes to it. Two siblings have no direct way to read each other's state.
Here is a search box and a result list. Each looks reasonable alone, but they cannot work together.
import { useState } from 'react';
function SearchBox() {
const [query, setQuery] = useState('');
return <input value={query} onChange={(e) => setQuery(e.target.value)} />;
}
function ResultList() {
// This component has no way to know what the user typed.
return <ul><li>Apple</li><li>Apricot</li><li>Banana</li></ul>;
}The query lives inside SearchBox, and ResultList needs it. Copying the value into a second useState would give you two sources of truth that drift apart.
The fix: move state to the closest common parent
Lifting state up means deleting the state from the children, adding it to the nearest parent that contains every component that needs it, and passing it back down as props. Children that need to change the value receive a callback prop.
import { useState } from 'react';
const FRUITS = ['Apple', 'Apricot', 'Banana', 'Cherry'];
function SearchBox({ query, onQueryChange }) {
return (
<input
value={query}
onChange={(event) => onQueryChange(event.target.value)}
placeholder="Search fruit"
/>
);
}
function ResultList({ query }) {
const visible = FRUITS.filter((fruit) =>
fruit.toLowerCase().includes(query.toLowerCase())
);
return (
<ul>
{visible.map((fruit) => (
<li key={fruit}>{fruit}</li>
))}
</ul>
);
}
export function FruitSearch() {
const [query, setQuery] = useState('');
return (
<>
<SearchBox query={query} onQueryChange={setQuery} />
<ResultList query={query} />
</>
);
}FruitSearch is now the single source of truth. SearchBox is a controlled component: its value comes from props, and it reports changes upward. The next chapters on controlled and uncontrolled components build on this idea.
A checklist for lifting
- Find every component that reads or changes the value.
- Find their closest common parent. Lifting higher than that only widens the blast radius.
- Remove the
useStatefrom the children and add it to that parent. - Pass the value down as a prop and pass a setter or handler down as a callback.
- Check that no child still keeps its own copy of the value.
Step 5 is the common error. A child that initializes its own state from a prop, such as useState(props.query), only reads the prop on the first render. Later prop changes are ignored, and the copy goes stale.
Limit 1: prop drilling
Lifting works well when the owner and the consumers are one or two levels apart. As the tree grows, intermediate components must accept and forward props they never use. This is called prop drilling.
function Page({ query, onQueryChange }) {
return <Layout query={query} onQueryChange={onQueryChange} />;
}
function Layout({ query, onQueryChange }) {
// Layout does not use query. It only forwards it.
return <Sidebar query={query} onQueryChange={onQueryChange} />;
}
function Sidebar({ query, onQueryChange }) {
return <SearchBox query={query} onQueryChange={onQueryChange} />;
}The costs are concrete. Renaming a prop means editing every layer. Adding a second shared value means editing every layer again. Components such as Layout can no longer be reused without also carrying a query prop they do not care about.
There are two ways out. The first is composition: build the SearchBox element at the top and pass it down as children or a named prop, so the intermediate layers never see the data. The second is context, which the chapter on sharing state with context covers.
Limit 2: the parent grows into a god component
Every lifted value adds one more useState and more handlers to the owner. After a few rounds, the parent holds state that most of its own code does not use, and it passes ten props to each child. The parent also needs to know the internal details of its children, such as which value a date picker needs for its open state.
Ask whether the parent really needs the state. Some state is only relevant to one widget, such as whether a dropdown is open. If no outside code reads it, keep it local.
Limit 3: re-renders spread
When state changes, React re-renders the component that owns it and, by default, all of its descendants. Lifting state higher means a keystroke in SearchBox re-renders everything under FruitSearch, including components unrelated to the query.
For small trees this does not matter. When it does, you have these options:
- Move the state back down, or split it so that fast-changing values live in a smaller subtree.
- Pass unrelated subtrees as
children. Elements created by a higher component keep the same identity when the lower owner re-renders, so React can skip them. - Wrap expensive children in
React.memo, and keep their props stable.
Limit 4: the consumer must wire everything by hand
Lifted state puts the burden on the person using your components. If you build a Tabs component with one lifted value, every consumer must create the state, pass value to the tab list, pass value to each panel, and keep the two in sync. Getting one prop wrong breaks the widget silently.
This is the main motivation for compound components. The widget owns its own state internally and shares it with its parts through context, so the consumer only arranges the parts. Lifted state is still available when the consumer wants control, which is what the control props chapter covers.
When to lift and when not to
| Situation | Better choice |
|---|---|
| Two nearby siblings need the same value | Lift state to the parent |
| Only one component reads and writes the value | Keep it local |
| A value passes through three or more components that ignore it | Composition or context |
| Several components repeat the same state and handler logic | A custom hook |
| A reusable widget whose parts must coordinate | Compound components |
Common errors
- Duplicating state. Keeping both a lifted value and a local copy. Derive values during render instead of storing them. In
ResultList,visibleis computed fromqueryand is not stored in state. - Lifting too high. Moving state to the app root "just in case". Lift only to the closest common parent.
- Mutating lifted state. Handlers that modify an array or object in place do not trigger a re-render. Create a new array or object.
- Missing callbacks. Passing
querytoSearchBoxwithoutonQueryChangeproduces an input that cannot be edited. React warns when avaluehas noonChange.
Exercise
A Page component renders Header and Content. Both Header (a badge showing the number of selected items) and Content (a list with checkboxes) need the selected item IDs. Where should the selectedIds state live, and what does Content need to receive so it can change the selection?
Show answer
The state belongs in Page, the closest common parent of Header and Content. Header receives selectedIds (or just its length) as a prop. Content receives selectedIds and a callback such as onToggle(id) or onSelectionChange(nextIds), which it calls when a checkbox changes. The handler in Page must build a new array rather than mutating the existing one.
Exercise
A teammate writes function SearchBox({ query }) { const [text, setText] = useState(query); ... } and wonders why the input ignores changes the parent makes to query after the first render. What is the cause, and how do you fix it?
Show answer
useState(query) uses the prop only as the initial value on the first render, so the local text becomes a second source of truth that never updates from later prop changes. Remove the local state and read query directly. Report edits through an onQueryChange callback so the parent stays the single owner.