Sub topic 9
Deciding which component should own state
This chapter assumes you can write function components, use useState, pass props and callbacks, and have seen the sibling-sync problem and the idea of lifting state. Here you learn how to pick the component that should hold a piece of state.
Start with the readers and writers
Every piece of state has components that read it and components that change it. List both groups, then ask one question: which component is the closest common parent of all of them? That component is the owner.
Use this procedure:
- Name the piece of state, such as
queryoractiveIndex. - List every component that displays it or depends on it.
- List every component that needs to change it.
- Find the lowest component in the tree that contains all of them.
- Put the state there. If no component contains them all, add a wrapper component above them.
The owner does not have to be the top of the app. It only has to be the lowest component that contains every reader and writer.
A worked example
Suppose a page has a search box, a list of fruit, and a "Like" button on each row. Check each piece of state against the procedure:
queryis written bySearchBarand read by the list that filters. Their closest common parent isApp, soAppowns it.likedis read and written only by oneRow. Nothing else cares, so it stays inRow.
import { useState } from 'react';
const FRUITS = ['Apple', 'Apricot', 'Banana', 'Cherry'];
function SearchBar({ query, onQueryChange }) {
return (
<input
value={query}
onChange={e => onQueryChange(e.target.value)}
placeholder="Search"
/>
);
}
function Row({ name }) {
const [liked, setLiked] = useState(false);
return (
<li>
{name}{' '}
<button onClick={() => setLiked(!liked)}>
{liked ? 'Liked' : 'Like'}
</button>
</li>
);
}
function ResultList({ items }) {
return (
<ul>
{items.map(name => (
<Row key={name} name={name} />
))}
</ul>
);
}
export default function App() {
const [query, setQuery] = useState('');
const visible = FRUITS.filter(name =>
name.toLowerCase().includes(query.toLowerCase())
);
return (
<>
<SearchBar query={query} onQueryChange={setQuery} />
<ResultList items={visible} />
</>
);
}App stores only query. The filtered list is computed during render, so it cannot fall out of step with the query.
Keep state as low as it can go
Lifting is a response to a real need, not a default. State in a high component re-renders more of the tree when it changes. It also forces props through components that don't care about it. Two habits help:
- Start local. Lift only when a second component needs the value.
- When a lifted value is no longer shared, for example after a redesign removes one reader, move it back down.
Check for signs of the wrong owner
| Symptom | Likely cause | Fix |
|---|---|---|
| Two components show different values for the same thing | Each has its own copy | Lift to the closest common parent |
| A parent holds state that only one child uses | Over-lifting | Move the state into that child |
| A prop is passed through several components that ignore it | Owner is far from the consumer | Try composition or context |
| State is a copy of a prop or of other state | Duplicated state | Derive the value during render |
Decide by the rules the state enforces
Sometimes the deciding factor is a rule across components. In the accordion from the topic plan, "only one panel is open" cannot be enforced by a single panel. The parent stores one activeIndex, and each panel receives isActive and an onShow callback. When a rule involves several siblings, the parent must own the state that expresses it.
Exercise
A page has a Cart component that shows an item count, a ProductList where each product has an "Add" button, and a ProductCard that tracks whether its details panel is expanded. Which component should own the cart items, and which should own the expanded flag?
Show answer
The cart items are read by Cart and written by the Add buttons in ProductList, so the closest common parent of both owns them. Pass the items down to Cart and an add callback down to the products. The expanded flag is used only by its own ProductCard, so it stays local there.