Sub topic 13
Iterate: refine the hierarchy and know the trade-offs
This chapter assumes you have finished the five steps on the product table. You have a component hierarchy, a static version, two pieces of state (filterText and inStockOnly), state owned by FilterableProductTable, and callback props that carry changes back up. You should be comfortable with function components, props, useState, and Array.prototype.filter.
The version you have works. This chapter covers what to do next: refine the structure without changing behavior, and recognize the costs of the choices you made.
Treat the first hierarchy as a draft
The five steps give you a design that works, not a final one. Writing real code often shows that your first split was slightly off. Common signs are:
- A component does two jobs. The first
ProductTablefilters, groups, and renders. - The same markup or logic appears in two places.
- A component receives props it only passes along.
- A piece of logic is hard to test because it is buried in JSX.
Refining means changing the structure while the visible behavior stays the same. You run through the same loop each time: notice a problem, make one small change, check that the UI still behaves the same.
Refinement 1: separate the data logic from the rendering
In the previous chapter, ProductTable did three things in one loop. It skipped rows that did not match, tracked lastCategory to insert headings, and built JSX. The filter rules are plain JavaScript and have nothing to do with React. Moving them into pure functions makes them easy to read, reuse, and test.
The following code runs in Node as shown.
const PRODUCTS = [
{ category: 'Fruits', price: '$1', stocked: true, name: 'Apple' },
{ category: 'Fruits', price: '$1', stocked: true, name: 'Dragonfruit' },
{ category: 'Fruits', price: '$2', stocked: false, name: 'Passionfruit' },
{ category: 'Vegetables', price: '$2', stocked: true, name: 'Spinach' },
{ category: 'Vegetables', price: '$4', stocked: false, name: 'Pumpkin' },
{ category: 'Vegetables', price: '$1', stocked: true, name: 'Peas' }
];
function filterProducts(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 groupByCategory(products) {
const groups = new Map();
for (const product of products) {
if (!groups.has(product.category)) {
groups.set(product.category, []);
}
groups.get(product.category).push(product);
}
return groups;
}
const visible = filterProducts(PRODUCTS, 'p', true);
const groups = groupByCategory(visible);
for (const [category, items] of groups) {
console.log(`${category}: ${items.map((p) => p.name).join(', ')}`);
}This prints:
Fruits: Apple
Vegetables: Spinach, PeasBoth functions take their inputs as arguments and return a new value without changing anything. This is the same idea as derived data. The filtered list is computed from products, filterText, and inStockOnly, and it is never stored.
ProductTable now only turns data into elements:
function ProductTable({ products, filterText, inStockOnly }) {
const visible = filterProducts(products, filterText, inStockOnly);
const groups = groupByCategory(visible);
const rows = [];
groups.forEach((items, category) => {
rows.push(
<ProductCategoryRow category={category} key={`category:${category}`} />
);
items.forEach((product) => {
rows.push(<ProductRow product={product} key={`product:${product.name}`} />);
});
});
return (
<table>
<thead>
<tr>
<th>Name</th>
<th>Price</th>
</tr>
</thead>
<tbody>{rows}</tbody>
</table>
);
}The refactor fixes two weaknesses of the earlier loop.
- Unsorted data. The
lastCategorytrick only works if products of the same category sit next to each other in the array. If the array were ordered Apple, Spinach, Dragonfruit, the table would show "Fruits" twice, with the same key, which React warns about.groupByCategorydoes not depend on the input order. - Key collisions. The earlier code used
product.categoryandproduct.nameas keys in one shared array. A product named "Fruits" would collide with the Fruits heading. Thecategory:andproduct:prefixes make each key unique within the array.
Refinement 2: use stable ids as keys
The keys above are still built from name. That works for six rows in a demo, but a name is not a reliable identity. Two products can share a name, and a name can be edited. Real data usually comes with an id from a database, and that id should be the key.
const PRODUCTS = [
{ id: 1, category: 'Fruits', price: '$1', stocked: true, name: 'Apple' },
{ id: 2, category: 'Fruits', price: '$1', stocked: true, name: 'Dragonfruit' }
];Then use key={product:${product.id}}. Keys matter most when rows hold state, such as an input inside a row. If the key changes, React discards the row's state and creates it again. If two different rows share a key, their state can end up attached to the wrong row.
Never use the array index as the key when rows can be filtered, sorted, or reordered. Typing in the search box changes which products sit at each index, so the key would no longer identify the same product.
Refinement 3: check whether a component earns its place
Splitting is cheap, but it is not always an improvement. Ask these questions about each component.
- Does it have one clear responsibility that you can name in a short phrase?
- Does it map to a section of the mockup or a unit of data?
- Is it used more than once, or does it isolate something that would otherwise be hard to read?
ProductCategoryRow and ProductRow pass this test. They are small, each does one job, and each matches one visible row type. A new TableHeader component for the two <th> cells would be harmless but gain you very little. Do not extract it until the header gains behavior, such as sorting by column.
The reverse mistake is also common. A SearchBar that renders two inputs and nothing else is fine. If it also fetched data or held its own copy of the filter text, it would have too many jobs.
Trade-offs you accepted
Each decision in the five steps has a cost. Knowing the cost tells you when to revisit the decision.
| Decision | Benefit | Cost | When to revisit |
|---|---|---|---|
| State lives in the closest common parent | One source of truth, so the search bar and table cannot disagree | Every change re-renders the parent and its children | When profiling shows the re-renders are slow |
| Pass data as props | Each component is easy to understand and test alone | Props that pass through components that don't use them (prop drilling) | When the same props pass through three or more levels |
| Derive the visible rows during render | No stale copy to keep in sync | The filter runs on every render | When the list is very large |
| Controlled inputs | The UI always matches state, and you can validate or transform input | Every keystroke goes through React state | Rarely. Use uncontrolled inputs only for simple forms where you read the value on submit |
| Callback props for inverse data flow | Data flow stays explicit and traceable | More props to wire up | When there are many callbacks, group them or use a reducer or context |
Prop drilling
In this app, filterText goes from FilterableProductTable to ProductTable and from there to nothing deeper, which is fine. If the table had a Section, then a Group, then a Row that needed filterText to highlight matches, each layer in between would have to carry a prop it never uses. Two reasonable fixes are:
- Restructure with composition. Pass already-built elements as
childrenso the middle layers do not need the props. - Use context for data that many distant components read.
Try composition first. Context makes the data flow harder to follow, because a component's inputs no longer appear in its parameter list.
Re-rendering on every keystroke
Each character typed calls setFilterText, so FilterableProductTable renders again, and so do SearchBar and ProductTable. For six products this costs nothing. Add optimizations only after you measure a problem. Options, from simplest to most involved:
useMemoaroundfilterProductswhen the list is large and the filter is expensive.React.memoon row components so unchanged rows are skipped.useDeferredValueon the filter text to keep typing responsive while the list catches up.- Virtualization, which renders only the rows currently on screen, for thousands of rows.
Where else could state live?
React state in the parent is the simplest choice here, but it is not the only one. If users should be able to share a link to a filtered view, filterText belongs in the URL query string. If the same filter must survive page reloads, it could go in localStorage. The reasoning is the same as before: pick one source of truth, and derive everything else from it.
Common errors when iterating
- Changing behavior while refactoring. If you move logic and change a condition at the same time, you cannot tell which change broke the UI. Do one at a time.
- Duplicating state during a refactor. Adding a
visibleProductsstate next to the filter state recreates the stale data problem. - Mutating the products prop. Calling
products.sort()insideProductTablereorders the parent's array in place. Copy first with[...products].sort(...). - Unstable keys. Using index or
Math.random()as a key makes React recreate every row on each render and drops any state in them. - Moving state too high. If only
SearchBarneeded a piece of state, keeping it there is simpler. Lift state only when a second component needs it.
Exercise
A teammate adds a state variable visibleProducts and updates it inside onFilterTextChange and onInStockOnlyChange, "so the table doesn't recompute rows". Name two problems with this design and describe the fix.
Show answer
First, visibleProducts is derived data: it can be computed from products, filterText, and inStockOnly, so storing it adds a second source of truth that can go stale. For example, if products changes and nobody updates visibleProducts, the table shows old rows. Second, two handlers now have to remember to update it in step with the other state, and any new place that changes a filter must do the same. The fix is to delete visibleProducts, compute filterProducts(products, filterText, inStockOnly) during render, and wrap it in useMemo only if profiling shows the filter is too slow.
Exercise
The product array is reordered so that the items are Apple, Spinach, Dragonfruit. What happens to the table built with the lastCategory loop from the previous chapter, and how does groupByCategory avoid it?
Show answer
The lastCategory loop adds a heading whenever the category differs from the previous product's category, so it renders "Fruits", "Vegetables", "Fruits" with a duplicate heading and a duplicate key, which makes React warn. groupByCategory collects products into a Map keyed by category, so each category appears once no matter how the input is ordered, and headings are rendered once per group.
Exercise
Why is key={index} a poor choice for the product rows in a filterable table, and what should you use?
Show answer
When the filter changes, different products occupy each index, so React matches a row to the wrong product and may reuse or discard row state incorrectly. Use a stable, unique id from the data, such as product.id, prefixed if the same array also holds other kinds of rows.