Sub topic 2
The cost of memoizing by hand
This chapter assumes you know function components, props and state, and the useState, useEffect, useMemo and useCallback hooks. You should also know that React re-renders a component when its state changes or its parent re-renders. The chapter explains what hand-written memoization does, what it costs you, and where it commonly goes wrong. That explains why the React Compiler exists.
What manual memoization is for
Memoization means saving the result of a computation and reusing it when the inputs have not changed. React gives you three tools for this:
| Tool | What it caches | Reused while |
|---|---|---|
| `React.memo(Component)` | The rendered output of a component | Its props are shallowly equal to the previous props |
| `useMemo(fn, deps)` | The value returned by `fn` | Every item in `deps` is the same (`Object.is`) |
| `useCallback(fn, deps)` | The function `fn` itself | Every item in `deps` is the same (`Object.is`) |
These tools solve two separate problems.
- Expensive work. Filtering or sorting a large list on every render wastes time.
useMemoskips the work when its inputs are unchanged. - Unstable references. In JavaScript,
{}is not equal to{}, and two separately created functions are never equal. Each render creates new objects and functions. A child wrapped inmemocompares props withObject.is, so a new function prop on every render defeatsmemo.useCallbackanduseMemokeep the reference the same, somemocan skip the child.
Here is the list component from this tutorial's running example. It uses all three tools.
import { memo, useCallback, useMemo, useState } from 'react';
const Row = memo(function Row({ item, onSelect }) {
return <li onClick={() => onSelect(item.id)}>{item.name}</li>;
});
export function List({ items }) {
const [query, setQuery] = useState('');
const [selectedId, setSelectedId] = useState(null);
const visible = useMemo(
() => items.filter((i) => i.name.includes(query)),
[items, query]
);
const handleSelect = useCallback((id) => setSelectedId(id), []);
return (
<>
<input value={query} onChange={(e) => setQuery(e.target.value)} />
<p>Selected: {selectedId}</p>
<ul>
{visible.map((item) => (
<Row key={item.id} item={item} onSelect={handleSelect} />
))}
</ul>
</>
);
}Each piece has a job:
memoonRowlets a row skip rendering whenitemandonSelectare unchanged.useCallbackkeepshandleSelectthe same function across renders. Without it, every render would pass a newonSelectand every row would re-render.useMemokeepsvisiblethe same array whileitemsandqueryare unchanged. That avoids refiltering, and it also keeps the list reference stable.
Notice that the code works the same without any of this. Memoization changes only how much work React does, never what appears on screen. That fact is what makes it both safe to add and easy to get wrong.
The costs
You must decide where to put it
Nothing tells you which components or values need memoization. You have to profile, or guess. Many teams react by wrapping everything, which adds noise. Others wrap nothing and pay for it later. Either way, the choice is a judgment call repeated at every component, and the code does not record why you made it.
Readability suffers
Compare the memoized List above with the same component without memoization.
import { useState } from 'react';
function Row({ item, onSelect }) {
return <li onClick={() => onSelect(item.id)}>{item.name}</li>;
}
export function List({ items }) {
const [query, setQuery] = useState('');
const [selectedId, setSelectedId] = useState(null);
const visible = items.filter((i) => i.name.includes(query));
const handleSelect = (id) => setSelectedId(id);
return (
<>
<input value={query} onChange={(e) => setQuery(e.target.value)} />
<p>Selected: {selectedId}</p>
<ul>
{visible.map((item) => (
<Row key={item.id} item={item} onSelect={handleSelect} />
))}
</ul>
</>
);
}The second version is shorter and shows the intent directly. The first adds wrappers, dependency arrays and an extra import line, and a reader must work out what each one protects.
Dependency arrays are easy to get wrong
Every useMemo and useCallback needs a dependency array. Two mistakes are common.
A missing dependency gives you a stale value. This code never updates the filtered list when query changes:
const visible = useMemo(
() => items.filter((i) => i.name.includes(query)),
[items] // query is missing, so the result is never recomputed for a new query
);The react-hooks/exhaustive-deps lint rule catches this case. It can still be silenced with a comment, and teams often do that to get past an annoying warning.
An unstable dependency defeats the cache. If a dependency is an object or function created during render, it changes every time, and the memoized value is recomputed every time:
function Results({ items, query }) {
const options = { query }; // new object on every render
const visible = useMemo(
() => filterItems(items, options),
[items, options] // options changes each render, so the cache never hits
);
return <Table rows={visible} />;
}This code still works. It is simply slower than expected, and nothing reports a problem. You only find out by profiling.
One missed reference breaks the chain
Memoization only helps if every link holds. Suppose List memoizes handleSelect but passes style={{ color: 'red' }} to Row. That inline object is new on every render, so memo sees a changed prop and re-renders every row. The memo, useCallback and useMemo you wrote still run, and they now add comparison work while saving nothing.
<Row
key={item.id}
item={item}
onSelect={handleSelect}
style={{ color: 'red' }} // new object each render, so memo(Row) never skips
/>The same happens with children. A JSX child such as <Row><b>hi</b></Row> creates a new element object on every render of the parent, so a memoized Row that receives children re-renders every time.
Memoization is not free
Each useMemo or useCallback costs memory to keep the cached value and its dependencies. It also costs time, because React compares the dependency array on every render. For cheap computations, that comparison can cost about as much as the work you saved. memo adds a shallow props comparison on every parent render, which is wasted effort for a component that almost always receives new props.
A rough decision guide when writing by hand:
- Skip memoization for cheap work and for components that usually render with new props.
- Memoize when profiling shows an expensive computation or a slow subtree.
- Memoize a value or function when it is a prop of a
memocomponent, or a dependency of a hook such asuseEffect, and its identity matters.
It is easy to leave out and hard to notice
Because memoized and unmemoized code behave identically, no test fails when someone adds an inline callback to a memoized path. Performance degrades quietly. Memoization also tends to rot. A teammate edits a useMemo body, forgets to update the array, and introduces a stale-value bug that appears only in some situations.
It sits awkwardly with conditions
Hooks cannot be called conditionally or after an early return. If a component has a guard clause, you cannot memoize a value that is computed after it:
function Profile({ user }) {
if (!user) return null;
// Error: React Hook "useMemo" is called conditionally.
const fullName = useMemo(() => `${user.first} ${user.last}`, [user]);
return <h1>{fullName}</h1>;
}You must restructure the component, for example by moving the computation above the early return and handling user being null inside it. This is extra work whose only purpose is to satisfy the hook rules.
Putting it together
The next diagram shows how a single unstable value undoes the other work.
The costs above fall into one pattern. The tools are correct, but using them well requires you to track references and dependencies across the whole component by hand, and the compiler is the same job done by a program. A tool that analyzes the code at build time can do that bookkeeping without the mistakes above. The next chapters show how the React Compiler does this, and what it needs from your code in return.
Summary table of costs
| Cost | Symptom | How you notice |
|---|---|---|
| Deciding where to memoize | Inconsistent, noisy code | Code review disagreements |
| Missing dependency | Stale values on screen | Bug reports, lint warning |
| Unstable dependency | Cache never hits | Profiling only |
| One unstable prop | `memo` never skips | React DevTools Profiler |
| Overuse | Extra memory and comparison time | Profiling only |
| Hook placement rules | Awkward restructuring | Lint error |
Exercise
A Row component is wrapped in React.memo, and its parent passes onSelect={handleSelect} where handleSelect is wrapped in useCallback. The parent also passes options={{ dense: true }}. Rows still re-render whenever the parent re-renders. Why, and how do you fix it?
Show answer
The inline object { dense: true } is created on every render, so memo sees a new options prop each time and never skips the row. Fix it by moving the object outside the component, because it is a constant, or by creating it with useMemo if it depends on props or state. Alternatively, pass the primitive value dense={true} instead of an object.
Exercise
Why can useMemo(() => compute(items, options), [items, options]) recompute on every render when options is declared as const options = { query }; inside the component?
Show answer
options is a new object on every render, so its reference differs from the previous render and the dependency comparison with Object.is always fails. The memoized function runs every time. Memoize options itself, or list query as the dependency and build the object inside the callback.
Exercise
Give two reasons a team might end up with slower or buggier code after adding useMemo and useCallback everywhere.
Show answer
Possible answers: each hook adds memory use and a dependency comparison on every render, which can cost as much as the work it saves for cheap computations. Wrong or missing dependencies cause stale values. Unstable dependencies or props make the caches miss while still paying the comparison cost. Any two of these is correct.