Sub topic 2
The cost of memoizing by hand
This chapter assumes you know function components, props and state, and the useState, useMemo and useCallback hooks. You should also know that React re-renders a component when its state changes or when its parent re-renders.
What manual memoization is
Memoization means saving the result of a computation so you can reuse it when the inputs have not changed. React gives you three tools for this:
React.memowraps a component. React skips re-rendering it when its props are shallowly equal to the previous props.useMemocaches a computed value between renders until a dependency changes.useCallbackcaches a function so it keeps the same identity between renders until a dependency changes.
These tools work together. A function defined inside a component is a new object on every render. If you pass it to a memo child, the child sees a changed prop and re-renders anyway. You have to stabilize the function with useCallback for memo to help.
A hand-memoized list
This component re-renders on every keystroke in the input. The goal is to keep each Row from re-rendering when only query or the "Selected" text changes.
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 of the three pieces does a job. memo lets Row bail out. useCallback keeps onSelect stable so that bail-out works. useMemo keeps visible from being recomputed when only selectedId changes.
Where the cost comes from
Hand-written memoization has real costs.
- More code to read. The logic is the same as the plain version, with extra wrappers and dependency arrays around it.
- Dependency arrays you must keep correct. If you leave out a dependency, the cached value goes stale and the UI shows old data. If you add an unstable dependency, such as an object created during render, the cache is invalidated every time and the hook does nothing useful.
- Chains that break silently.
memoonly helps if every prop is stable. One inline arrow function or object literal passed to a memoized child cancels the benefit, and nothing warns you. - Decisions that go stale. You memoize something today. A later edit changes a prop and the optimization stops working, or the memoized code is no longer expensive and nobody removes it.
- Its own overhead. Memoization costs memory and comparison work. Wrapping cheap components or trivial calculations can make them slower, not faster.
The following table sums up the common failure modes.
| Mistake | Effect |
|---|---|
| Missing dependency in `useMemo` or `useCallback` | Stale values and subtle bugs |
| Object or array literal in a dependency array | Cache is rebuilt on every render |
| Inline function passed to a `memo` child | The child re-renders every time |
| Memoizing cheap work | Extra memory and comparisons, no gain |
Why this matters for the compiler
Almost every rule above is mechanical. You decide what to cache, list the inputs, and keep the list accurate. Mechanical rules that humans apply inconsistently are a good job for a tool. This is the problem the React Compiler targets. It analyzes your components at build time and inserts the caching for you, so the plain version of the list, with no wrappers, can behave like the memoized one.
Exercise
A parent passes onSelect={(id) => setSelectedId(id)} as an inline function to a child wrapped in React.memo. The parent re-renders when the user types in a search box. Does the child skip rendering? Why, and how do you fix it by hand?
Show answer
No. The inline arrow function is created again on every parent render, so its identity changes. memo compares props shallowly, sees a different onSelect, and re-renders the child. Fix it by wrapping the handler in useCallback((id) => setSelectedId(id), []), so the same function is passed on every render.
Exercise
Name two ways a dependency array in useMemo can be wrong, and the visible symptom of each.
Show answer
A missing dependency leaves the cached value stale, so the UI shows outdated data. An unstable dependency, such as an object literal created during render, changes on every render, so the cache never hits and the memoization gives no benefit.