Sub topic 7
Caching values with useMemo
This chapter assumes you know function components, JSX, useState, useEffect, and how props and children move between components. It also assumes you know that JavaScript objects, arrays, and functions are reference values, so two separate {} literals are never equal under ===. The previous chapters covered why components re-render, how to measure with the Profiler, and how React.memo compares props.
What useMemo does
useMemo is a hook that remembers the result of a calculation between renders. You give it a function and a list of dependencies. React runs the function on the first render and stores the result. On later renders, React compares each dependency with the value from the previous render. If none changed, React returns the stored result and skips the function. If one changed, React runs the function again and stores the new result.
const value = useMemo(() => compute(a, b), [a, b]);The function you pass is called the calculation function. It runs during rendering, so it must be pure: it takes its inputs from props, state, and other values in the component, and it does not change anything outside itself.
useMemo serves two different purposes. Keep them separate in your head, because they have different tests for when they are worth using:
- Skip an expensive calculation when its inputs have not changed.
- Keep an object or array reference stable, so that a memoized child or another hook's dependency array sees "no change".
Purpose 1: skipping expensive calculations
Consider a product list with a text filter and a theme toggle. Toggling the theme changes state, so the component re-renders. Without caching, every theme toggle filters the whole product array again, even though neither products nor query changed.
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>
);
}When you click "Toggle theme", darkMode changes, but products and query are the same as before. React returns the cached visible array and does not call filter. When you type in the input, query changes, so React runs the filter again.
The component still re-renders on every theme toggle, and its JSX is still rebuilt. useMemo only saves the work inside the calculation function. It does not stop the component from rendering.
How to decide if a calculation is expensive
A calculation is worth caching when it takes noticeable time on a realistic data size. Do not guess. You can time it directly with console.time and console.timeEnd around the calculation, using the data a real user would have.
console.time('filter products');
const visible = products.filter((p) =>
p.name.toLowerCase().includes(query.toLowerCase())
);
console.timeEnd('filter products');A common rule of thumb is to consider caching when the calculation takes about 1 millisecond or more. Run the measurement with CPU throttling enabled in the browser's performance tools, because your development machine is usually faster than your users' devices. Also measure a production build, since development builds are slower and add extra checks.
Filtering 50 items takes microseconds, so memoizing it adds code and comparison work for no visible gain. Filtering 50,000 items, or running a sort and a group-by over thousands of rows, can take tens of milliseconds and may be worth caching.
Purpose 2: keeping references stable
The second purpose has nothing to do with how long the calculation takes. It is about identity. Recall from the earlier chapters that React.memo compares props with Object.is. An object literal written during render creates a new object every time, so the comparison always fails.
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} />
</>
);
}Each click on the button re-renders Dashboard. Because options comes from useMemo with an empty dependency array, it is the same object on every render, so Chart skips its render. With the inline literal, Chart would log "render chart" on every click.
The same idea applies when the object is passed to a hook. If options appears in a useEffect dependency array, a new object each render would make the effect run each time. A memoized object keeps the effect quiet until a real input changes.
For this purpose, useMemo only pays off when something downstream compares the reference. That means a memo-wrapped child, a dependency array, or a context value. If the child is not memoized, a stable reference changes nothing, because the child re-renders whenever its parent does.
A concrete decision flow
The following diagram shows the questions to ask before adding useMemo.
Dependencies and how they are compared
The dependency array tells React which values the calculation reads. React compares each entry with its previous value using Object.is. This is the same comparison that memo uses for props, so everything from the referential equality chapter applies.
Follow these rules:
- List every reactive value the calculation function reads: props, state, and variables declared in the component body.
- Do not list values that are not reactive, such as module-level constants or imports.
- Treat the array as a contract. Do not leave out a value to "avoid recalculating". That produces stale results.
Here is a stale-value bug:
import { useMemo } from 'react';
export function PriceTag({ price, taxRate }) {
// Bug: taxRate is read inside the function but missing from the array.
const total = useMemo(() => price * (1 + taxRate), [price]);
return <span>{total.toFixed(2)}</span>;
}If taxRate changes while price stays the same, total keeps the old value. The react-hooks/exhaustive-deps ESLint rule catches this. Enable it and treat its warnings as errors.
Dependencies that are objects
A dependency that is itself an unstable object defeats the cache. In this example filters is created in the parent on every render, so the memoized list is recomputed every time:
import { useMemo } from 'react';
export function Results({ items, filters }) {
// Recomputes on every render if the parent passes a fresh filters object.
const shown = useMemo(
() => items.filter((item) => item.type === filters.type),
[items, filters]
);
return <p>{shown.length} results</p>;
}Two fixes work. You can stabilize filters in the parent with useMemo. Or you can depend on the primitive you actually read, which compares by value:
import { useMemo } from 'react';
export function Results({ items, filters }) {
const type = filters.type;
const shown = useMemo(
() => items.filter((item) => item.type === type),
[items, type]
);
return <p>{shown.length} results</p>;
}Depending on primitives is often the simplest way to get a stable dependency.
Common errors
| Mistake | What happens | Fix |
|---|---|---|
| Missing dependency | The cached value goes stale | Enable `exhaustive-deps` and list every reactive value |
| Mutating the cached array, for example `sort()` on it | Other code sees changed data, and React cannot detect the change | Copy first with `[...list].sort()` or `toSorted()` |
| Memoizing a value passed to a non-memoized child | No effect, because the child re-renders anyway | Memoize the child too, or remove the `useMemo` |
| Calling `useMemo` inside a loop or condition | Breaks the rules of hooks | Move the work into a child component |
| Expecting a guarantee | React may discard cached values in some situations | Treat `useMemo` as a performance hint, not a semantic guarantee |
The last row matters for correctness. Your code must still produce correct output if React recalculates the value. Never use useMemo to hold state or to make something run only once. Use useState, useRef, or an effect for that.
Mutation example
Sorting mutates the array it is called on. If you sort a prop or a memoized array in place, you change data you do not own:
import { useMemo } from 'react';
export function SortedList({ items }) {
const sorted = useMemo(
() => [...items].sort((a, b) => a.name.localeCompare(b.name)),
[items]
);
return (
<ul>
{sorted.map((item) => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
}The spread creates a copy, so items stays untouched.
Memoizing per item in a list
You cannot call useMemo inside items.map(...), because hooks cannot run in loops. If each row needs a cached value, move the row into its own component and call useMemo there. Often that component is also wrapped in memo, which skips the whole row when its props are unchanged. Use this approach when each row does costly work, not by default.
What useMemo costs
Caching is not free. Each useMemo call stores the previous result and dependencies in memory. On every render React runs the dependency comparison. The calculation function you pass is also created on every render, even when React does not call it. For a cheap calculation, this overhead can exceed the cost of just doing the work. Extra useMemo calls also make code harder to read, because readers must check each dependency array.
For that reason, the next chapters cover cheaper alternatives, such as moving state down, and the cases where memoization has no effect. Add useMemo after a measurement shows a problem, and re-measure afterward to confirm the problem is gone.
Exercise
A component receives rows (a prop with 20,000 objects) and sortKey (a string). It also has a highlighted state that changes whenever the user hovers over a row. The component sorts rows by sortKey during render, and hovering feels slow. Write the useMemo call that fixes this, and explain what the dependency array must contain and why you copy the array.
Show answer
const sorted = useMemo(() => [...rows].sort((a, b) => String(a[sortKey]).localeCompare(String(b[sortKey]))), [rows, sortKey]); The array lists rows and sortKey because the calculation reads both, so hovering (which only changes highlighted) reuses the cached result. The copy with the spread operator keeps sort from mutating the rows prop.
Exercise
A parent passes style={{ color: 'red' }} to a child wrapped in memo. The child still re-renders every time the parent does. You wrap the style in useMemo, but the child still re-renders. Name two likely causes.
Show answer
First, another prop is unstable, for example an inline function or array, so memo still sees a changed prop. Second, the useMemo dependency array contains a value that changes every render, which recreates the object each time. A third possibility is that the child receives children as JSX, which is also a new object on each parent render.