Sub topic 4
Caching Expensive Calculations with useMemo
Where this chapter fits
This chapter assumes you can write function components, use useState and props, and read a useEffect dependency array. The previous chapter showed that a value computable from props and state should be calculated during render, not copied into state by an Effect. That raises a question: what if the calculation is slow? This chapter covers useMemo, the tool for that case, along with how to tell whether you need it and the mistakes that make it fail quietly.
The tempting but wrong fix
Suppose a component filters a long list of todos. You may be tempted to treat the filtered list as state and keep it up to date with an Effect:
import { useState, useEffect } from 'react';
function TodoList({ todos, filter }) {
const [visibleTodos, setVisibleTodos] = useState([]);
// Avoid: redundant state and an unnecessary Effect
useEffect(() => {
setVisibleTodos(getFilteredTodos(todos, filter));
}, [todos, filter]);
return (
<ul>
{visibleTodos.map(todo => (
<li key={todo.id}>{todo.text}</li>
))}
</ul>
);
}This version has three problems:
- Wrong output on the first paint. The first render shows an empty list because
visibleTodosstarts as[]. The Effect runs after React paints, so the user sees a stale or empty list before the real one arrives. - Extra work. When
todosorfilterchanges, React renders with the oldvisibleTodos, runs the Effect, callssetVisibleTodos, and renders again. That is two render passes for one change. - A state variable that can drift.
visibleTodosis a copy of information that already exists intodosandfilter. Any copy can fall out of sync with its source.
The Effect does not make the slow filtering any faster. It only moves it to a worse place.
Calculate in render, then cache if needed
The first step is to calculate the value in the component body. For most components, that is all you need. If the calculation is genuinely slow, wrap it in useMemo:
import { useMemo } from 'react';
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>
);
}useMemo takes two arguments:
- A calculation function with no arguments that returns the value. React calls it during rendering.
- A dependency array listing every reactive value the calculation reads, such as props, state, and variables derived from them.
On the first render, React calls your function and stores the result. On later renders, React compares each dependency with the value from the previous render, using Object.is. If none changed, it returns the stored result and skips the function. If any changed, it calls the function again and stores the new result.
Nothing here involves state or an Effect. The value is still derived during render, and useMemo only controls how often the derivation runs.
A complete example you can run
This example makes the benefit visible. Typing in the "note" box re-renders the parent on every keystroke. Because todos and filter do not change during typing, the filter runs only when you change the filter.
import { useMemo, useState } from 'react';
const allTodos = Array.from({ length: 5000 }, (_, i) => ({
id: i,
text: 'Task ' + i,
completed: i % 3 === 0,
}));
function getFilteredTodos(todos, filter) {
console.log('Filtering ' + todos.length + ' todos for "' + filter + '"');
return todos.filter(todo => {
if (filter === 'active') return !todo.completed;
if (filter === 'completed') return todo.completed;
return true;
});
}
function TodoList({ todos, filter }) {
const visibleTodos = useMemo(
() => getFilteredTodos(todos, filter),
[todos, filter]
);
return <p>{visibleTodos.length} todos shown</p>;
}
export default function App() {
const [filter, setFilter] = useState('all');
const [note, setNote] = useState('');
return (
<>
<select value={filter} onChange={e => setFilter(e.target.value)}>
<option value="all">All</option>
<option value="active">Active</option>
<option value="completed">Completed</option>
</select>
<input
value={note}
onChange={e => setNote(e.target.value)}
placeholder="Type a note"
/>
<TodoList todos={allTodos} filter={filter} />
</>
);
}Open the console and type in the note box. After the first render, the "Filtering" message does not appear again, because the dependencies are unchanged. Change the select and it appears once per change.
In development, React Strict Mode calls your calculation function twice on each recalculation to help you spot impure code. You may see the log message twice. This does not happen in production.
Deciding whether a calculation is expensive
Most calculations are cheap. Filtering a list of ten items, concatenating strings, or doing arithmetic costs almost nothing. Wrapping these in useMemo adds code, adds a dependency array to maintain, and gains nothing.
Measure first. Wrap the calculation in a timer:
console.time('filter todos');
const visibleTodos = getFilteredTodos(todos, filter);
console.timeEnd('filter todos');As a rule of thumb from the React documentation, consider caching when the logged time adds up to about 1 ms or more. Keep these points in mind while measuring:
- Test with realistic data. A list of 5 items in development tells you little about 5,000 in production.
- Slow down the CPU. Your development machine is probably faster than your users' devices. Chrome DevTools lets you throttle the CPU so the effect of a slow calculation shows up.
- Use a production build. Development builds are slower and do extra checks, so timings from them are inflated.
- Know that memoization does not speed up the first render. It only skips repeat work on later renders when the inputs have not changed.
Caching also has a cost. React must store the previous result and compare dependencies on every render. For cheap work, that overhead can exceed the work saved.
When useMemo does not help
useMemo pays off only when the component re-renders for reasons unrelated to the calculation's inputs. If every render changes todos or filter, the cache never hits. Before adding useMemo, consider cheaper structural fixes:
- Move state down. If a fast-changing input like a text box lives in a parent that also owns an expensive list, move the input into its own component so it does not re-render the list.
- Calculate less. Sometimes a calculation can use a better algorithm, a lookup table, or pagination.
- Skip child renders with
memo.useMemocaches a value inside one component. To avoid re-rendering a slow child whose props are unchanged, wrap that child inReact.memo. These solve different problems.
| Tool | What it caches | Typical use |
|---|---|---|
| `useMemo` | A value computed during render | An expensive filter, sort, or transformation |
| `memo` | A component's rendered output, based on props | Skipping a slow child when its props are unchanged |
| Moving state down | Nothing, it avoids the re-render | A fast-changing input that causes unrelated re-renders |
Common errors
Unstable dependencies
useMemo compares dependencies with Object.is. Objects and arrays created during render are new every time, so they always look changed:
function TodoList({ todos, filterText }) {
// New object on every render, so the cache never hits
const options = { text: filterText, caseSensitive: false };
const visibleTodos = useMemo(
() => getFilteredTodos(todos, options),
[todos, options]
);
// ...
}The fix is to depend on the primitive values the calculation actually uses, or to create the object inside the calculation:
const visibleTodos = useMemo(
() => getFilteredTodos(todos, { text: filterText, caseSensitive: false }),
[todos, filterText]
);The same problem appears when a parent passes a freshly created array or object as a prop. Memoization in the child then fails because of what the parent does.
Missing or wrong dependencies
If the calculation reads a value that is not in the array, useMemo keeps returning an old result after that value changes. This is a silent bug. Enable the react-hooks/exhaustive-deps lint rule and follow it. Do not delete a dependency to make the cache hit more often. If the cache misses too much, fix why the dependency changes.
An impure calculation
The function you pass must be pure. It should compute a result from its inputs and nothing else. Do not make network requests, write to the DOM, or call setState inside it. Do not mutate todos either. todos.sort(...) sorts the original array in place, which corrupts props. Copy first:
const sortedTodos = useMemo(
() => [...todos].sort((a, b) => a.text.localeCompare(b.text)),
[todos]
);Strict Mode's double call helps expose these mistakes. If the two calls give different results or visible side effects, the function is not pure.
Treating useMemo as a guarantee
useMemo is a performance hint. React may discard cached values, for example while a component is being edited with Fast Refresh or when it suspends before it has mounted. Your code must remain correct if the calculation reruns. Do not use useMemo to hold something that must stay the same for correctness. Use useState or useRef for that.
Calling it conditionally
useMemo is a Hook, so it follows the rules of Hooks. Call it at the top level of the component, not inside conditions, loops, or nested functions. To memoize work for each item in a list, extract a child component that calls useMemo itself.
Why not an Effect for expensive work
It may seem that "run only when inputs change" is exactly what an Effect's dependency array does. The difference is when the code runs and what it does with the result:
- An Effect runs after the render is painted. To use its result, it must store the result in state, which triggers another render.
useMemoruns during the render and returns the value directly. The component renders once with the correct data.
Use an Effect to synchronize with something outside React, and useMemo to remember a pure result.
Summary of the decision
- If the value can be computed from props and state, compute it during render. Do not create state for it.
- If it is cheap, stop there.
- If you measure a real cost, and the inputs change less often than the component renders, wrap the calculation in
useMemowith a complete dependency array. - If the cache keeps missing, look for unstable dependencies or move state down.
Exercise
A component keeps fullName in state and updates it in an Effect that depends on firstName and lastName. A teammate suggests wrapping the Effect's work in useMemo to "make it faster." What is the better change, and why?
Show answer
Remove the fullName state and the Effect, and calculate const fullName = firstName + ' ' + lastName; in the component body. String concatenation is far too cheap to need useMemo, and the Effect version causes an extra render pass and can show stale data on the first paint. useMemo would not remove either problem, because the root cause is redundant state, not slow work.
Exercise
This component re-runs getFilteredTodos on every render even though it uses useMemo. Find the cause and fix it.
function TodoList({ todos, filterText }) {
const options = { text: filterText };
const visible = useMemo(
() => getFilteredTodos(todos, options),
[todos, options]
);
return <p>{visible.length}</p>;
}
Show answer
options is a new object on every render, so Object.is reports a change and the cache never hits. Create the object inside the calculation and depend on the primitive filterText instead: useMemo(() => getFilteredTodos(todos, { text: filterText }), [todos, filterText]). Then the calculation reruns only when todos or filterText changes.
Exercise
You wrapped a calculation in useMemo, and later React discards the cached value and runs the calculation again. Should your app break? What does this tell you about what the calculation may do?
Show answer
The app should not break. useMemo is a performance optimization, not a guarantee, so React may drop cached values. This means the calculation must be pure: it should only compute a result from its inputs, with no side effects and no mutation of props or state, so running it again gives the same result.