Sub topic 9
Compute filtered rows during render instead of storing them
This chapter assumes you can write a function component, use useState, and read the product table from earlier chapters. It covers one decision: the filtered list of products is derived data, so you compute it while rendering and never store it in state.
The tempting mistake
The search box and checkbox change what the table shows. A common first instinct is to keep a third piece of state, visibleProducts, and update it whenever the user types or clicks.
That design creates two sources of truth. The filter inputs say one thing and the stored list says another. If you forget to update the list in one handler, the table shows stale rows. Nothing in React will warn you.
Derived data
Data is derived when you can calculate it from props or state you already have. The filtered rows depend only on three values:
products, which arrives as a prop.filterText, which is state.inStockOnly, which is state.
Because the visible rows follow from those three values, they are not state. You calculate them each time the component renders.
Filtering inside ProductTable
ProductTable receives the full products array plus the two filter values. It skips any product that does not match, then builds the rows as before.
function ProductTable({ products, filterText, inStockOnly }) {
const rows = [];
let lastCategory = null;
products.forEach((product) => {
if (!product.name.toLowerCase().includes(filterText.toLowerCase())) {
return;
}
if (inStockOnly && !product.stocked) {
return;
}
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>
);
}There are three details to notice:
- Both text values are lowercased, so searching for
appmatchesApple. - A
returninsideforEachskips only the current product. The loop continues. - The category check runs after filtering. Because
lastCategoryis updated only for products that pass, a category heading appears only when at least one of its products is visible. If you search forpeas, the Fruits heading disappears.
Why this is the right design
Compare the two approaches.
| Approach | Sources of truth | Risk |
|---|---|---|
| Store `visibleProducts` in state | Filter inputs and the stored list | The two can disagree after a missed update |
| Derive rows during render | Filter inputs only | None of that kind, because rows are recalculated every time |
When a user types, the setter updates filterText. React re-renders FilterableProductTable, which passes the new value to ProductTable. The table runs the loop again and shows the correct rows. No handler needs to know how filtering works.
Common errors
- Copying a prop into state.
useState(products)for the list you filter creates a copy that will not follow later changes to the prop. - Filtering in the parent and passing only the result down. This works, but then the parent must also own the filtering logic. Keeping it in
ProductTableleavesSearchBarand the parent simple. - Forgetting
toLowerCase()on both sides. Only one side gives case-sensitive matches in surprising places.
A quick test for derived data
Ask of any value: can I compute this from props or other state? If yes, compute it. If you find yourself writing an effect or a handler whose only job is to keep one value in sync with another, that value is probably derived.
Exercise
A teammate adds const [visibleProducts, setVisibleProducts] = useState(products) and updates it inside both onChange handlers. Give one bug this can cause and describe the fix.
Show answer
The stored list can go out of sync with the inputs. For example, if products changes (a new item is added) and no handler runs, visibleProducts still holds the old array, so the new item never appears. The fix is to remove visibleProducts, keep only filterText and inStockOnly as state, and filter products inside ProductTable during render.
Exercise
In the filtering loop, why does searching for peas hide the Fruits heading?
Show answer
The category row is pushed only for products that pass both filters, and only when product.category !== lastCategory. No fruit passes the text filter, so no fruit reaches the category check, and no Fruits heading is added.