Sub topic 12
When memoization does not pay off
This chapter assumes you know function components, useState, props, and that objects, arrays and functions are compared by reference. It also assumes you have met React.memo, useMemo and useCallback. Here you will learn when they add cost, when they do nothing, and what to try first.
Memoization has a price
Every memoized value costs something on each render. React must store the previous result and dependencies, compare the dependencies, and keep the cached value in memory. If the work you skip is cheaper than this bookkeeping, you lose time overall.
Memoization also makes code harder to read. A reader must check each dependency array and ask whether a missing dependency causes stale data.
Cases where memoization has no effect
These patterns look like optimizations but skip nothing.
- An unstable prop reaches a memoized child. If
Chartis wrapped inmemobut the parent passesoptions={{ color: 'blue' }}, the object is new on every render.memosees a changed prop and re-renders anyway. - The component always receives new props. If a prop really changes on every render, such as a timestamp,
memocompares and then renders every time. useCallbackfeeds a child that is not memoized. A stable function only helps if the receiver checks its props. A plain child re-renders when its parent does, whatever the function identity.useMemowraps a trivial calculation. Cachinga + bor a smallmapover five items costs more than recomputing it.- Children passed as JSX. An element like
<Row />created in the parent is a new object each render, so a memoized wrapper that receives it aschildrenis not skipped.
import { memo, useCallback, useState } from 'react';
const Label = memo(function Label({ text }) {
console.log('render label');
return <span>{text}</span>;
});
export function Counter() {
const [count, setCount] = useState(0);
// Wasteful: the callback is stable, but nothing downstream checks it.
const increment = useCallback(() => setCount((c) => c + 1), []);
return (
<>
<button onClick={increment}>Clicked {count}</button>
{/* Label has a stable string prop, so memo works here. */}
<Label text="Counter" />
</>
);
}In this example Label is skipped because text is a string, which compares by value. The useCallback call adds nothing, because button is a built-in element that is cheap to update.
Decide with a short checklist
Ask these questions in order before adding memoization.
- Did the Profiler show a slow render? If not, stop.
- Can the state move down into a smaller component? See the example below.
- Can the slow part be passed as
children, so it is created by a parent that does not re-render? - Only then, wrap the expensive component in
memoand stabilize every prop it receives.
State that lives too high is a common root cause. Moving it down removes the re-render instead of hiding it.
import { useState } from 'react';
export function Page() {
return (
<>
<SearchBox />
<ExpensiveTree />
</>
);
}
function SearchBox() {
const [query, setQuery] = useState('');
return <input value={query} onChange={(e) => setQuery(e.target.value)} />;
}
function ExpensiveTree() {
// Imagine a large subtree here.
return <div>Large content</div>;
}Typing updates only SearchBox. Page does not re-render, so ExpensiveTree is untouched and needs no memo.
When memoization is worth it
Memoization pays off when three things are true. The component is expensive to render or has a large subtree. It re-renders often with props that did not change. Every prop it receives is stable. A useMemo is also justified for a calculation that the Profiler shows to be slow, such as filtering thousands of rows.
Remember that useMemo is a performance hint, not a guarantee. Write code that stays correct if the cache is dropped.
Exercise
A parent holds a query state and renders <Results items={items} onPick={() => pick(id)} />, where Results is wrapped in memo. Typing in the input still re-renders Results every time. Give two reasons the memo is ineffective and one cheaper fix to try first.
Show answer
The inline arrow function onPick is a new reference on every render, so memo sees a changed prop. If items is built inline in the parent (for example with .filter or a literal), it is also a new reference each time. A cheaper fix is to move the query state and input into their own component, so the parent that renders Results no longer re-renders while typing. Stabilizing onPick with useCallback and items with useMemo is the fallback.