Sub topic 7
Caching values with useMemo
This chapter assumes you know function components, useState, and how JavaScript compares objects and arrays by reference. It also assumes you have read the earlier chapters on referential equality, React.memo, and dependency arrays.
What useMemo does
useMemo is a hook that remembers the result of a calculation between renders. You give it a function and a dependency array. React runs the function on the first render and stores the result. On later renders, React compares each dependency with its previous value using Object.is. If none changed, it returns the stored result and skips the function. If one changed, it runs the function again and stores the new result.
const value = useMemo(() => compute(a, b), [a, b]);useMemo has two common uses:
- Skipping an expensive calculation when its inputs have not changed.
- Keeping an object or array reference stable so a memoized child does not re-render.
Use 1: skip expensive work
The component below filters a product list. Without useMemo, the filter runs on every render, including renders caused only by the theme toggle.
import { useMemo, useState } from 'react';
export function ProductList({ products }) {
const [query, setQuery] = useState('');
const [darkMode, setDarkMode] = useState(false);
const visible = useMemo(
() => products.filter((p) => p.name.toLowerCase().includes(query.toLowerCase())),
[products, query]
);
return (
<div className={darkMode ? 'dark' : 'light'}>
<input value={query} onChange={(e) => setQuery(e.target.value)} />
<button onClick={() => setDarkMode((d) => !d)}>Toggle theme</button>
<ul>
{visible.map((p) => (
<li key={p.id}>{p.name}</li>
))}
</ul>
</div>
);
}The dependencies are products and query, the two values the callback reads. Toggling the theme changes neither, so React returns the cached visible array.
Use 2: keep a reference stable
An object literal creates a new object on every render. A memo child compares props by reference, so it sees a changed prop and re-renders. useMemo returns the same object until its dependencies change.
import { memo, useMemo, useState } from 'react';
const Chart = memo(function Chart({ options }) {
console.log('render chart');
return <div>{options.color}</div>;
});
export function Dashboard() {
const [count, setCount] = useState(0);
// Broken: a new object on every render, so memo sees a changed prop.
// <Chart options={{ color: 'blue' }} />
// Fixed: the same object is reused until its dependencies change.
const options = useMemo(() => ({ color: 'blue' }), []);
return (
<>
<button onClick={() => setCount(count + 1)}>Clicked {count}</button>
<Chart options={options} />
</>
);
}Clicking the button re-renders Dashboard, but Chart is skipped. Here the calculation is trivial. The value of useMemo is the stable reference, not the saved work.
Common errors
- Missing dependencies. If the callback reads
querybut the array omits it, the cached result goes stale and the UI shows old data. Include every reactive value the callback reads. - Unstable dependencies. If a dependency is itself a new object each render, the cache is rebuilt every time and
useMemodoes nothing but add cost. - Treating it as a guarantee. React may discard cached values in some situations. Your code must stay correct if the function runs again.
- Side effects inside the callback. The function should only calculate and return a value. Put effects in
useEffect. - Memoizing cheap work. Remembering a result has its own cost. Measure with the Profiler before adding
useMemoto simple calculations.
Choosing between the two uses
| Situation | Reason for useMemo |
|---|---|
| Filtering or sorting a large list | Skip the repeated calculation |
| Passing an object or array to a `memo` child | Keep the reference stable |
| Using an object as a dependency of another hook | Stop the hook from re-running on every render |
| Computing a small string or number | Usually not needed |
Exercise
A component computes const config = { theme, size }; and passes config to a memo child. The child still re-renders every time the parent re-renders, even when theme and size are unchanged. Rewrite the line so the child can skip those renders, and explain why it works.
Show answer
Use const config = useMemo(() => ({ theme, size }), [theme, size]);. The object literal creates a new reference on each render, so memo sees a changed prop. With useMemo, React returns the same object while theme and size keep their values, so the shallow comparison in memo finds the prop unchanged and skips the render.
Exercise
Why can leaving query out of the dependency array in the ProductList example cause a bug?
Show answer
The cached visible array is only recomputed when a listed dependency changes. Without query, typing in the input changes the state but not the dependencies, so React keeps returning the old filtered list and the displayed results do not match the input.