Sub topic 4
Caching expensive calculations with useMemo
This chapter assumes you know function components, useState, props, and how a component re-renders when state or props change. It also assumes you have read the previous chapter on calculating derived values during render.
The problem: a derived value that is slow to compute
Computing a value during render is the right default. Sometimes the calculation is slow, though, and the component re-renders for reasons that have nothing to do with it. Typing in an unrelated input re-renders the whole component. If that render also filters ten thousand todos, each keystroke feels sluggish.
The tempting fix is to store the result in state and update it with an Effect:
// Avoid this: redundant state plus an Effect.
const [visibleTodos, setVisibleTodos] = useState([]);
useEffect(() => {
setVisibleTodos(getFilteredTodos(todos, filter));
}, [todos, filter]);This renders once with a stale (empty) list, runs the Effect, sets state, and renders again. It does the slow work anyway and adds a second render. The fix is to cache the calculation and keep it inside render.
Caching with useMemo
useMemo takes a function and a dependency array. React calls the function during the first render and stores the result. On later renders it compares each dependency with its previous value. If none changed, React returns the stored result without calling your function.
import { useMemo } from 'react';
function getFilteredTodos(todos, filter) {
return todos.filter(todo => {
if (filter === 'active') return !todo.done;
if (filter === 'completed') return todo.done;
return true;
});
}
function TodoList({ todos, filter }) {
const visibleTodos = useMemo(
() => getFilteredTodos(todos, filter),
[todos, filter]
);
return (
<ul>
{visibleTodos.map(todo => (
<li key={todo.id}>{todo.text}</li>
))}
</ul>
);
}There is no state variable and no Effect. visibleTodos is still a plain value computed from props.
Decide whether you need it
Most calculations are fast. Wrapping all of them in useMemo adds code and a dependency array to maintain, and it gains nothing. Measure first:
console.time('filter');
const visibleTodos = getFilteredTodos(todos, filter);
console.timeEnd('filter');As a rule of thumb, consider useMemo when the logged time is around 1 ms or more. Test with realistic data, and keep in mind that development builds and fast machines can hide a problem that slower devices will show. You can also throttle the CPU in your browser's developer tools to simulate a slower device.
Keep one point in mind. useMemo does not make the first render faster. It only skips repeated work on later renders when the inputs are unchanged.
Rules and gotchas
- The calculation must be pure. React may call it more than once in development, and it may discard cached values and recompute. Do not put side effects in it.
- Dependencies are compared with
Object.is. If a parent builds a newtodosarray on every render, the cache never hits. Memoization only helps when the inputs keep the same identity between renders. - List every reactive value you read. If the function uses
filter, thenfilterbelongs in the array. Leaving it out returns stale results. - Treat it as a performance hint. Your code must still be correct if React recomputes. Do not rely on
useMemoto preserve meaning, such as keeping an identity that your logic depends on.
useMemo versus the alternatives
| Situation | Better tool |
|---|---|
| Cheap calculation | Plain expression in the component body |
| Slow calculation, same inputs across renders | `useMemo` |
| Need fresh state when a prop changes | A `key` on the component |
| Work caused by a click or submit | Event handler |
Summary of the idea
useMemo is a cache for derived values. It does not replace derived values with state, and it does not replace calculation with synchronization. If you find yourself reaching for an Effect plus setState to store a computed result, calculate it during render, and add useMemo only after measuring a real cost.
Exercise
A component computes const sorted = useMemo(() => sortItems(items), [items]);, but the parent writes <List items={data.filter(isVisible)} />. Profiling shows sortItems runs on every render. Why, and how would you fix it?
Show answer
data.filter(isVisible) creates a new array on every parent render, so items has a new identity each time and Object.is reports a change. The cache never hits. Fix it by memoizing the filtered array in the parent with useMemo(() => data.filter(isVisible), [data]), or by doing the filtering inside List within the same memoized calculation.