Sub topic 10
Step 4: Decide where state should live
This chapter assumes you finished the earlier steps. You have a component hierarchy, a static version that renders only from props, and a list of the state the UI needs: filterText and inStockOnly. You should also know how useState returns a value and a setter.
Step 3 told you what the state is. Step 4 answers a different question: which component owns each piece of state? An owner is the component that calls useState for that value. Every other component that needs the value receives it as a prop.
The procedure
React's guidance for this step has three parts. Run them once for each piece of state.
- Identify every component that renders something based on that state.
- Find their closest common parent, which is the lowest component in the tree that contains all of them.
- Put the state in that parent. If it makes no sense there, put it in a component above it. If no component fits, create a new component just to hold the state, and place it above the common parent.
The parts are ordered on purpose. The state must sit in an ancestor of every component that reads it, because props only travel downward. Among the valid ancestors, you pick the lowest one, because that keeps changes local.
Applying it to the product table
The hierarchy from Step 1 looks like this:
FilterableProductTableSearchBarProductTableProductCategoryRowProductRow
For each piece of state, list the consumers.
| State | Who uses it | Closest common parent |
|---|---|---|
| `filterText` | `SearchBar` displays it in the text box. `ProductTable` uses it to drop rows whose names don't match. | `FilterableProductTable` |
| `inStockOnly` | `SearchBar` displays it as the checkbox state. `ProductTable` uses it to drop out-of-stock rows. | `FilterableProductTable` |
SearchBar and ProductTable are siblings. Neither contains the other, so the lowest component that contains both is their parent. Both pieces of state belong there.
The code
The owner calls useState and passes both the values and the setters down. The setters travel as callback props, which Step 5 puts to work.
import { useState } from 'react';
function FilterableProductTable({ products }) {
const [filterText, setFilterText] = useState('');
const [inStockOnly, setInStockOnly] = useState(false);
return (
<div>
<SearchBar
filterText={filterText}
inStockOnly={inStockOnly}
onFilterTextChange={setFilterText}
onInStockOnlyChange={setInStockOnly}
/>
<ProductTable
products={products}
filterText={filterText}
inStockOnly={inStockOnly}
/>
</div>
);
}Three details are worth noting.
- The initial values,
''andfalse, describe the unfiltered table. The first render shows every product. ProductTablereceives the rawproductsarray and the two filter values. It does not receive a pre-filtered list. The filtered rows are derived data, so they are computed during render as in Step 3.FilterableProductTableis the only component that callssetFilterTextorsetInStockOnlydirectly. It hands the setters toSearchBarunder names that describe events, such asonFilterTextChange.
What you see at this point
If SearchBar still reads its values from props but has no onChange handlers yet, the page shows the right starting state and then refuses to change. Here is that intermediate version of SearchBar:
function SearchBar({ filterText, inStockOnly }) {
return (
<form>
<input type="text" value={filterText} placeholder="Search..." />
<label>
<input type="checkbox" checked={inStockOnly} />{' '}
Only show products in stock
</label>
</form>
);
}Typing in the box does nothing, and the console warns that you provided a value prop to a form field without an onChange handler. The input is controlled, so React forces it to display exactly the prop value. Because no code updates that prop, the displayed value never changes. This is expected after Step 4. Step 5 adds the handlers that let the user's input reach the state.
Why not somewhere else
The common parent is not the only place the code will compile. It is the only place that keeps the design simple. Compare the alternatives for filterText.
| Placement | What happens |
|---|---|
| Inside `SearchBar` | The text box works, but `ProductTable` is a sibling and cannot read the value. The table never filters. |
| Inside `ProductTable` | The table can filter, but `SearchBar` cannot read or set the value. |
| In both children | There are two copies that drift apart. The text box and the table disagree. |
| In `FilterableProductTable` | One copy, visible to every consumer. This is the correct choice. |
| In a root `App` above it | It works, but `App` now knows about a concern that only one subtree cares about. Every unrelated component under `App` is also a candidate for needless coupling. |
The first three rows break the app. The last row is merely too high. State that sits above its closest common parent still works, but readers of the code have to look farther to find it, and the parent's props grow to carry values it does not use itself.
Common errors
Keeping a second copy inside a child
A frequent mistake is to give SearchBar its own state seeded from the prop:
import { useState } from 'react';
function SearchBar({ filterText }) {
// Bug: copies the prop once and then ignores later changes.
const [text, setText] = useState(filterText);
return <input type="text" value={text} onChange={(e) => setText(e.target.value)} />;
}useState uses its argument only on the first render. If the parent later changes filterText, text does not follow. Meanwhile, nothing tells the parent about edits made to text, so ProductTable never filters. The rule is that each piece of data has one owner. Everyone else reads it through props.
Lifting state to a component that is not an ancestor
State can only reach descendants. If you add useState in a component that is not above every consumer, some consumer has no path to it. When you cannot find an existing component above all the consumers, create a new one for the purpose. It is common for a new wrapper component to appear at this step.
Lifting state too high "just in case"
Do not move state upward because you might need it elsewhere later. If only SearchBar cares about, say, whether a help tooltip is open, that boolean stays inside SearchBar. State that is used by one component and its children does not need an owner higher up. Move it up only when a second consumer outside that subtree appears.
Storing derived values as state
If you find yourself writing const [visibleProducts, setVisibleProducts] = useState(products), stop. Visible products are a function of products, filterText, and inStockOnly. Storing them creates a second source of truth that you must keep synchronized by hand. Compute them in ProductTable during render.
Edge cases and decision criteria
- A new consumer appears. Suppose the mockup gains a
DetailPanelthat shows the selected product, placed next to the table. State such asselectedProductis read byProductRow(to highlight) and byDetailPanel. Their closest common parent isFilterableProductTable, so that component gains a thirduseState. - Two pieces of state that always change together. If they never vary independently, consider whether one of them is really derived from the other. If they do vary independently, keep two separate
useStatecalls. Do not merge them just to reduce lines. - Sibling owners. It is valid for different pieces of state to have different owners. Run the procedure separately for each value. One value may live in
FilterableProductTablewhile another stays insideSearchBar. - Ownership changes. If you later find that the placement makes the code awkward, you can move the
useStatecall and adjust the props. This is cheap, because the data flow is explicit. Step 6 returns to this.
Summary of the decision
For each piece of state, list the components that read it, find the lowest component above all of them, and call useState there. Pass the value down as a prop. Pass the setter down as a callback prop so that descendants can request changes.
Exercise
The mockup adds a "Compare" feature. Each ProductRow gets a checkbox, and a new ComparePanel, placed beside ProductTable, lists the checked products. Which component should own the array of checked product names, and why?
Show answer
FilterableProductTable. The checked names are read by ProductRow (to show each checkbox) and by ComparePanel. ProductRow is inside ProductTable, and ComparePanel is its sibling, so the closest common parent of all consumers is FilterableProductTable. It holds the array with useState and passes it down, along with a callback for toggling a name.
Exercise
A teammate writes const [text, setText] = useState(filterText); inside SearchBar, where filterText is a prop from the parent. Typing in the box works, but the table never filters. Explain why, and say what to change.
Show answer
The initial value is copied once, so SearchBar edits its own private text and the parent's filterText never changes. ProductTable reads the parent's value, so it sees no change. Remove the local state. Let SearchBar use the filterText prop for value, and call a callback prop such as onFilterTextChange(e.target.value) in onChange, so the owner updates the single copy.