Sub topic 13
Iterate: refine the hierarchy and know the trade-offs
This chapter assumes you have built the searchable product table from the earlier chapters. That means FilterableProductTable owns filterText and inStockOnly, and SearchBar and ProductTable receive them as props. You should also be comfortable with props, useState, and callback props.
Treat the first hierarchy as a draft
The five-step process is a loop, not a straight line. When you wire up state, you often find that the hierarchy you drew from the mockup no longer fits.
Common reasons to go back:
- A component has gained a second job.
ProductTablenow loops, groups, and filters. - Two components need the same data, so the owner has to move up.
- A component takes many props only to pass them on.
Refine: pull the filtering out
The last version of ProductTable filters and builds rows in one loop. Filtering is a rule about data, not about layout. You can move it into a plain function that React doesn't need to know about.
function getVisibleProducts(products, filterText, inStockOnly) {
const query = filterText.toLowerCase();
return products.filter((product) => {
if (!product.name.toLowerCase().includes(query)) {
return false;
}
if (inStockOnly && !product.stocked) {
return false;
}
return true;
});
}
function ProductTable({ products, filterText, inStockOnly }) {
const visible = getVisibleProducts(products, filterText, inStockOnly);
const rows = [];
let lastCategory = null;
visible.forEach((product) => {
if (product.category !== lastCategory) {
rows.push(
<ProductCategoryRow
category={product.category}
key={product.category}
/>
);
}
rows.push(<ProductRow product={product} key={product.name} />);
lastCategory = product.category;
});
return (
<table>
<thead>
<tr>
<th>Name</th>
<th>Price</th>
</tr>
</thead>
<tbody>{rows}</tbody>
</table>
);
}ProductCategoryRow and ProductRow are unchanged from the static version. The behavior is the same, but you can now test getVisibleProducts without rendering anything. ProductTable is back to one job: turning a list into rows.
The result is still derived data. Nothing about the filtered list is stored in state.
Trade-offs to know
| Decision | Benefit | Cost |
|---|---|---|
| State in the common parent | One source of truth, no sync bugs | The parent re-renders on every keystroke, and so do its children |
| Deriving rows during render | Rows can never go stale | The filter runs again on each render |
| Passing props down | Data flow is easy to trace | Long chains of props that components only forward |
| Many small components | Each has one job | More files and more props to name |
For six products, none of these costs matters. Don't add useMemo or split components for performance until you measure a slow render. A filter over thousands of rows is the point where memoization may start to pay off.
If props are forwarded through several layers, first check whether the state owner is too high. If it really is shared widely, context is an option. It adds indirection, so it isn't a default.
Assumptions hidden in the example
- Grouping depends on sorted data. The
lastCategorycheck only works if products of one category are adjacent. Unsorted data gives you repeated headings and duplicate keys. - Keys assume unique names.
key={product.name}breaks if two products share a name. Real data should have anid. - Filtering is simple.
includeson lowercase text ignores accents, word boundaries, and ranking.
Common mistakes in this phase
- Storing the filtered array in state. It goes stale as soon as
productsor a filter changes. - Setting
valueon an input withoutonChange. The field becomes read-only. - Using the array index as a key for rows that get filtered. Rows shift position and React reuses the wrong elements.
- Copying a prop into state "to edit it". Later prop changes are ignored.
Exercise
A teammate adds a visibleProducts state variable to FilterableProductTable and updates it inside both onChange handlers. Which problem does this create, and what is the fix?
Show answer
The filtered list is derived data, so storing it duplicates information already held in products, filterText, and inStockOnly. The copy can drift out of sync, for example when products changes but no handler runs. Remove the state and compute the list during render, as getVisibleProducts does.
Exercise
Why might ProductTable show two "Fruits" headings if the products array is Apple, Pumpkin, Dragonfruit?
Show answer
The loop adds a category row whenever the category differs from the previous product's. With the order Fruits, Vegetables, Fruits, the category changes twice. Sort or group the data by category before looping.