Sub topic 9
Deciding which component should own state
This chapter assumes you can write function components, pass props, use useState, and handle events such as onChange. It also assumes you have seen the sibling sync problem and the basic lift-state-up move. Here the question is narrower: given a piece of state, which component should hold it?
Why placement matters
Every piece of state has one owner. The owner is the component that calls useState for it. Every other component that needs the value receives it as a prop. If the owner is too low, siblings cannot see the value. If it is too high, unrelated components re-render and you pass props through layers that do not care.
The goal is the lowest component that still covers everyone who needs the state. That component is the closest common parent of all readers and writers.
A four-step procedure
Use this checklist whenever you add or review a piece of state.
- List the components that read the value. These display it or compute something from it.
- List the components that change the value. These respond to events such as clicks or typing.
- Find their closest common parent in the component tree. If only one component is involved, it owns the state.
- Check whether the value is really state. If it can be computed from other state or props, do not store it.
Step 4 comes first in practice, because it can remove the whole question. A value that is derived during render never needs an owner.
Worked example: a filterable product list
Suppose you build a page with a search box, a list of products, and a result counter. The component tree looks like this:
ProductPageSearchBoxProductListResultCount
The search text is typed in SearchBox. It is read by ProductList to filter rows, and by ResultCount to report how many matched.
Apply the checklist to the search text.
- Readers:
ProductList,ResultCount, andSearchBoxitself, which displays the text. - Writers:
SearchBox. - Closest common parent:
ProductPage. - Derivable? No. The text comes from the user.
So ProductPage owns query. Now apply the same checklist to the filtered list. It is derivable from query and the product array, so it is not state.
import { useState } from 'react';
const PRODUCTS = [
{ id: 1, name: 'Apple' },
{ id: 2, name: 'Apricot' },
{ id: 3, name: 'Banana' },
{ id: 4, name: 'Blueberry' },
];
function SearchBox({ query, onQueryChange }) {
return (
<label>
Search:{' '}
<input value={query} onChange={e => onQueryChange(e.target.value)} />
</label>
);
}
function ProductList({ products }) {
return (
<ul>
{products.map(p => (
<li key={p.id}>{p.name}</li>
))}
</ul>
);
}
function ResultCount({ count }) {
return <p>{count} result(s)</p>;
}
export default function ProductPage() {
const [query, setQuery] = useState('');
const visible = PRODUCTS.filter(p =>
p.name.toLowerCase().includes(query.trim().toLowerCase())
);
return (
<>
<SearchBox query={query} onQueryChange={setQuery} />
<ResultCount count={visible.length} />
<ProductList products={visible} />
</>
);
}ProductPage holds one useState call. The filtered array is recomputed on every render and handed to two children. Neither child owns anything, so neither can disagree with the other.
What each placement costs
Putting state at the wrong level has different failure modes depending on which direction you miss.
| Placement | Typical symptom | Fix |
|---|---|---|
| Too low (inside one sibling) | Another component needs the value and has no access to it | Lift to the closest common parent |
| Too high (near the root) | Many components re-render on every keystroke, and long prop chains appear | Move state down to the lowest component that covers all users |
| Duplicated (in two places) | Values drift apart | Keep one copy and derive or pass the rest |
| In the parent but never read there | The parent exists only to relay props | Check whether composition or context fits better |
Signs the owner is too low
- You copy a value into a second component with an effect or a callback "to keep them in sync".
- A child needs to call something on its sibling.
- You find yourself wanting to read a child's state from the outside.
Each of these means the value has more than one user and needs a shared owner. Lift it.
Signs the owner is too high
- Typing in one input re-renders a large, unrelated part of the page.
- Several components in the middle of the tree accept a prop only to pass it on.
- The parent holds state that only one child ever reads.
For the last case, move the state back into that child. The next chapter covers this in detail.
Owners of related state
State that changes together often belongs together. In the accordion from earlier chapters, the parent stores one activeIndex instead of a boolean per panel. A single value makes illegal combinations, such as two open panels, impossible to represent.
When you lift several related values, consider grouping them in one object or one state variable so they update in a single call.
import { useState } from 'react';
export default function Filters() {
const [filters, setFilters] = useState({ query: '', inStockOnly: false });
function update(patch) {
setFilters(prev => ({ ...prev, ...patch }));
}
return (
<>
<input
value={filters.query}
onChange={e => update({ query: e.target.value })}
/>
<label>
<input
type="checkbox"
checked={filters.inStockOnly}
onChange={e => update({ inStockOnly: e.target.checked })}
/>
In stock only
</label>
</>
);
}The updater form setFilters(prev => ...) copies the previous object and overrides the changed fields. Writing filters.query = 'x' directly would mutate state, and React would not see a change.
Edge cases
Two possible parents
Sometimes it looks like more than one component could own the state. Choose the lowest one that contains every reader and writer. If a higher component also holds it "just in case", you create a second copy.
State that only looks shared
Two components may display similar data without needing to agree. Two independent search boxes on different pages are not siblings that must sync. Do not lift state merely because two components share a shape.
Values that belong to the URL or the server
Some values already have an owner outside React. A selected tab stored in the URL, or a list fetched from an API, should be read from that source. Copying it into useState creates a second truth that can go stale.
Moving the owner later
Ownership is not permanent. As the UI grows, a value that was local may need sharing, and a lifted value may stop needing it. Refactoring the owner means moving one useState call and updating the props. Because every other component only receives props, the change stays contained.
Common mistakes
- Choosing the root by default. It works, but it spreads props across the tree. Choose the closest common parent instead.
- Storing derived data. Keeping
visiblein state alongsidequeryguarantees they will eventually disagree. - Splitting one fact in two. Separate
isOpenandisClosedvariables can both be true. Use one. - Passing the setter and the value for unrelated reasons. Pass only what the child needs. A child that only reports changes needs a callback, not the whole state.
Exercise
A page has a Cart component that lists items, a CartBadge in the header that shows the item count, and a ProductCard that adds an item. All three are children of Shop. Which component should own the items array, and should the count be stored in state as well?
Show answer
Shop should own items, because it is the closest common parent of the readers (Cart, CartBadge) and the writer (ProductCard). The count should not be stored in state. Compute it during render as items.length and pass it to CartBadge, so it can never disagree with the list.
Exercise
A Sidebar keeps isCollapsed in useState. It is the only component that reads or changes the value, but the state was lifted to App earlier "in case other components need it". What is the cost, and what should you do?
Show answer
App re-renders on every toggle and must pass isCollapsed and a callback to Sidebar for no benefit. Since only Sidebar uses the value, move the useState call back into Sidebar and remove the props. Lift it again only when a second component needs it.