Sub topic 9
Compute filtered rows during render instead of storing them
This chapter assumes you can write function components and JSX, pass props, and use useState for a single value. It also assumes you have seen the static product table from the earlier chapters. Here you will learn why the filtered list of products should be computed while the component renders, and why it should not be stored in state.
The problem: two sources of truth
The search UI has two inputs: a text box and an "in stock only" checkbox. The table must show only the products that match both. A common first attempt is to keep the filtered list in state as well:
// Anti-pattern: do not copy this
const [filterText, setFilterText] = useState('');
const [inStockOnly, setInStockOnly] = useState(false);
const [visibleProducts, setVisibleProducts] = useState(products);Now three values describe one screen. Each time filterText or inStockOnly changes, you must also remember to update visibleProducts. If you forget one of those updates, the table shows rows that do not match the inputs. This is a bug that only appears for some sequences of user actions, so it is hard to find.
The fix follows from the previous chapter's rule: keep the minimal state. visibleProducts can be calculated from products, filterText, and inStockOnly. Data that you can calculate from existing props or state is called derived data. Derived data should not be state.
What counts as derived
Ask three questions about a piece of data, as in the minimal-state step:
- Does it stay unchanged over time? If so, it is not state.
- Is it passed in from a parent through props? If so, it is not state.
- Can you compute it from existing props or state? If so, it is not state.
The filtered list fails question 3. It is a function of three inputs:
visible rows = filter(products, filterText, inStockOnly)Because it is a pure function of its inputs, React can recompute it on every render and the result is always consistent with the inputs.
Filtering inside ProductTable
The state lives in FilterableProductTable and is passed down as props. ProductTable receives products, filterText, and inStockOnly. It builds its rows by skipping any product that does not match:
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 two filter checks, and each one uses an early return. Inside a forEach callback, return leaves only the current iteration. The loop then moves on to the next product.
The text check
if (!product.name.toLowerCase().includes(filterText.toLowerCase())) {
return;
}Both strings are lowercased so that "app" matches "Apple". The includes method checks for a substring, so "fruit" matches "Dragonfruit" and "Passionfruit". An empty filterText is a substring of every string, so the initial state '' shows every product. You do not need a special case for "no filter".
The stock check
if (inStockOnly && !product.stocked) {
return;
}When the checkbox is off, inStockOnly is false and the whole condition is false, so nothing is skipped. When it is on, products with stocked: false are skipped.
Category headings come after the filters
The order of the checks matters. The category heading is added only after a product has passed both filters. lastCategory is updated only for products that are actually shown. If you searched for "peas", the Fruits heading never appears, because no fruit reaches the rows.push calls.
Suppose you moved the heading check above the filters. Then every category would get a heading even when all of its products were filtered out, and you would see empty sections.
Following one change through the code
The sequence below shows what happens when the user types a letter.
Only two values are stored: filterText and inStockOnly. The list of rows is rebuilt from scratch on each render. The next render does not depend on the previous list of rows, so there is no stale list to clean up.
Worked example
Using the six products, the table below shows what each combination of inputs produces.
| `filterText` | `inStockOnly` | Rows shown |
|---|---|---|
| `''` | `false` | All six products, with both headings |
| `''` | `true` | Apple, Dragonfruit, Spinach, Peas |
| `'p'` | `false` | Apple, Passionfruit, Spinach, Pumpkin, Peas |
| `'p'` | `true` | Apple, Spinach, Peas |
| `'zzz'` | `false` | No rows and no headings |
The 'p' row is worth checking by hand. "Dragonfruit" contains no letter p, so it is dropped. "Apple" contains "p", so it stays. Every other product has a "p" in its name.
Why not store it, or cache it?
What goes wrong with stored copies
Storing the filtered list creates a synchronization problem. Related failure modes:
- Stale rows. You update
filterTextbut forgetvisibleProducts. The input and the table disagree. - Extra renders. If you update the copy in an effect, React renders once with the old copy and then again with the new one. The user may briefly see the wrong table.
- Stale data from props. If
productschanges in the parent, for example after a fetch, the stored copy still holds the old array. - Harder changes. Adding a third filter means updating every place that writes to the copy.
Is recomputing too slow?
For a list of six items, filtering costs almost nothing. For a few thousand items it is usually still fast, because the loop only does string comparisons. Do not optimize before you measure.
If profiling shows that filtering is slow, keep the data derived and wrap the calculation in useMemo. This caches the result and recomputes it only when the inputs change:
import { useMemo } from 'react';
function getVisibleProducts(products, filterText, inStockOnly) {
const needle = filterText.toLowerCase();
return products.filter((product) => {
if (!product.name.toLowerCase().includes(needle)) return false;
if (inStockOnly && !product.stocked) return false;
return true;
});
}
function useVisibleProducts(products, filterText, inStockOnly) {
return useMemo(
() => getVisibleProducts(products, filterText, inStockOnly),
[products, filterText, inStockOnly]
);
}useMemo is a cache, not a second source of truth. If React discarded the cached value, the next render would recompute the same result. The cache never holds information that the inputs do not already hold.
Common mistakes
- Mutating the products array. Calling
products.sort()orproducts.splice()inside render changes the original array. Usefilter, which returns a new array, or copy first with[...products]. - Filtering in the change handler. Calling
setVisibleProducts(...)insideonChangeis the stored-copy design again. - Forgetting case. Without
toLowerCase()on both sides, typing "apple" does not match "Apple". - Using the index as a key. Rows appear and disappear as the user types. Index keys then point to different products from one render to the next. Keep
key={product.name}so each row keeps its identity. - Putting the heading logic before the filters. This leaves empty category sections.
Exercises
Exercise
A teammate adds const [visibleProducts, setVisibleProducts] = useState(products) and updates it inside both onChange handlers. Give two reasons to replace this with computation during render, and say where the computation should go.
Show answer
The stored list can disagree with filterText and inStockOnly if any update path forgets to refresh it, and it goes stale when the products prop changes. It is also data that can be calculated from existing props and state, so it fails the minimal-state test. The computation belongs in ProductTable, which receives products, filterText, and inStockOnly as props and skips non-matching products while building its rows.
Exercise
With the six sample products, filterText is 'e' and inStockOnly is true. Which rows and headings are shown?
Show answer
Apple, Dragonfruit, Spinach, and Peas are in stock. Of these, "Apple" (ends in e), "Dragonfruit" (the letter e in "fruit"? no: D-r-a-g-o-n-f-r-u-i-t has no e), "Spinach" (no e), and "Peas" (has e) need checking. Apple and Peas contain "e"; Dragonfruit and Spinach do not. The table shows the Fruits heading with Apple, then the Vegetables heading with Peas.
Exercise
Add a third filter, a maximum price, to the design. Name the new state, say whether the filtered list becomes state, and describe the change to ProductTable.
Show answer
Add one state value, such as maxPrice, in FilterableProductTable, and pass it to ProductTable as a prop. The filtered list stays derived. In ProductTable, add a check such as if (Number(product.price.slice(1)) > maxPrice) return; before the category heading logic, so headings still appear only for categories that have visible rows.