Sub topic 12
When memoization does not pay off
This chapter assumes you already know how React.memo, useMemo and useCallback work. You should also know how referential equality and dependency arrays behave, and how to record a render in the React DevTools Profiler. The question here is when those tools should stay out of your code, because they cost something and sometimes do nothing.
Memoization has a price
Every memoization tool trades one cost for another.
React.memocompares every prop on every parent render. If the props differ, React renders the component anyway, so you paid for the comparison and got nothing back.useMemoanduseCallbackrun on every render. React compares the dependency array, and it keeps the previous value and dependencies in memory.- Each wrapper adds code to read, and each dependency array can be wrong in a way that no error message reports.
Most components render in well under a millisecond, so a skipped render rarely saves anything you could measure. Memoization pays off when the work skipped is larger than the work of checking whether it can be skipped. Anything else is overhead.
Also remember that useMemo is a performance hint, not a semantic guarantee. React may discard cached values, for example while offscreen content is being prepared. Your code must stay correct if the callback runs again.
Case 1: memo that never skips
A memoized component only skips a render when every prop is the same according to Object.is. A single unstable prop defeats it. The most common culprit is children, because JSX creates a new element object on every render of the parent.
import { memo, useState } from 'react';
const Panel = memo(function Panel({ title, children }) {
console.log('render panel');
return (
<section>
<h2>{title}</h2>
{children}
</section>
);
});
export function Screen() {
const [count, setCount] = useState(0);
return (
<>
<button onClick={() => setCount(count + 1)}>Clicked {count}</button>
<Panel title="Stats">
<p>Static text</p>
</Panel>
</>
);
}Panel logs on every click. The element <p>Static text</p> is a new object each time Screen runs, so the children prop never matches the previous one. The memo call costs a comparison per render and skips nothing.
You have three ways out, and the first two are cheaper than adding useMemo for the children:
- Move the
countstate into a small component that holds only the button, soScreenno longer re-renders. - Hoist the constant element outside the component, for example
const note = <p>Static text</p>;at module level. - Remove
memofromPaneland accept the render.
Once you know what to look for, the same pattern turns up in other props. An inline style={{ margin: 8 }}, an inline arrow function, and an array built with .map() during render all change identity on every render. If you cannot make every prop stable, memo on that component is dead weight.
Case 2: stable props passed to something that does not care
useCallback only helps when something downstream compares the function. Two situations make it pointless.
- The function goes to a DOM element such as
<button>. React does not compare event handler identity there. It just updates its internal handler. - The function goes to a child that is not wrapped in
memo. That child re-renders whenever its parent does, whatever the props are.
import { useCallback } from 'react';
export function Toolbar({ onSave }) {
// Pointless: <button> is a DOM element and nothing compares this function.
const handleClick = useCallback(() => {
onSave();
}, [onSave]);
return <button onClick={handleClick}>Save</button>;
}The simpler version has the same behavior and one fewer thing to maintain:
export function Toolbar({ onSave }) {
return <button onClick={() => onSave()}>Save</button>;
}A stable function is useful in only three places: as a prop to a memo component, as a dependency of another hook such as useEffect or useMemo, or as an argument to a custom hook that compares it. If your function is not used in one of those places, drop the useCallback.
Case 3: caching work that was already cheap
useMemo is worth it when the calculation is expensive or when it keeps an object or array stable for a memo child. It is not worth it for arithmetic or for a short list.
// Not worth it: the hook costs more than the multiplication.
const total = useMemo(() => price * quantity, [price, quantity]);
// Just compute it.
const total = price * quantity;Primitives need no caching for reference purposes. Object.is(42, 42) is already true, so a number or string prop never breaks memo. The only reason to cache a primitive is that computing it is slow.
To decide whether a calculation is slow, measure it. A quick check outside React gives you a rough number:
const products = Array.from({ length: 1000 }, (_, i) => ({
id: i,
name: `Product ${i}`,
}));
const query = 'prod';
console.time('filter');
const visible = products.filter((p) =>
p.name.toLowerCase().includes(query.toLowerCase())
);
console.timeEnd('filter');
console.log(visible.length);Run it a few times. On most machines filtering 1,000 short strings takes well under a millisecond, which is not worth a useMemo. The numbers change once the list reaches tens of thousands of items or the predicate does heavy work. Confirm the real cost with the Profiler in a production build, because development builds are noticeably slower and distort the picture.
Case 4: the parent re-render is the cheap part
A skipped render only saves time if the render was costly. If a component returns a handful of elements, rendering it takes microseconds. Wrapping hundreds of small components in memo adds hundreds of prop comparisons per update. The comparisons can cost as much as the renders they avoid.
Memoize at the boundary of an expensive subtree, such as a large table, a chart or a complex editor. Do not memoize each leaf inside it.
Case 5: context changes bypass memo
memo only guards against re-renders caused by a parent. A component that calls useContext re-renders whenever the context value changes, even if its props are identical and it is wrapped in memo.
import { createContext, memo, useContext, useState } from 'react';
const ThemeContext = createContext('light');
const Label = memo(function Label({ text }) {
const theme = useContext(ThemeContext);
console.log('render label');
return <span className={theme}>{text}</span>;
});
export function App() {
const [theme, setTheme] = useState('light');
return (
<ThemeContext.Provider value={theme}>
<button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
Toggle
</button>
<Label text="Hello" />
</ThemeContext.Provider>
);
}Toggling the theme re-renders Label, and that is correct, since its output depends on the theme. If a component should not update when part of the context changes, split the context into smaller ones or move the changing value closer to its consumers. Adding more memoization does not help.
Case 6: memoization that makes code wrong
A bad dependency array does more than waste effort. It can freeze a value and show stale data.
import { useCallback, useState } from 'react';
export function Counter() {
const [count, setCount] = useState(0);
// Bug: the empty array captures count = 0 forever.
const increment = useCallback(() => {
setCount(count + 1);
}, []);
return <button onClick={increment}>Count: {count}</button>;
}The button goes to 1 and stays there. Every call uses the count from the first render. Adding count to the dependencies fixes it but changes the function on every click, which removes the benefit. The functional update form fixes it and keeps the function stable:
const increment = useCallback(() => {
setCount((c) => c + 1);
}, []);If you find yourself fighting the linter's exhaustive-deps warning, treat that as a sign that the memoization is not worth keeping. Do not silence the rule.
A summary of the failures
| Situation | Why it does not help | Better option |
|---|---|---|
| `memo` child receives `children` as inline JSX | New element object each render | Move state down, or hoist the element |
| `memo` child receives an inline object or arrow function | New reference each render | Stabilize that prop, or remove `memo` |
| `useCallback` handler passed to a DOM element | Nothing compares the function | Use a plain inline function |
| `useCallback` handler passed to a child without `memo` | Child re-renders with its parent anyway | Add `memo` to the child, or drop the hook |
| `useMemo` around simple arithmetic | Hook overhead exceeds the work | Compute directly |
| `memo` on a context consumer, context changes | Context updates bypass `memo` | Split the context |
| Dependency array omits a value | Stale data | Fix the array or use a functional update |
A decision order
Work through the options from cheapest to most costly, and stop when the slowdown is gone.
The last step matters. If the second profile shows no gain, delete the memoization. A change that does not make the app faster only makes it harder to read.
Exercise
A Card component is wrapped in memo. Its parent re-renders on every keystroke in a search box and renders <Card title="Report"><Icon name="doc" /></Card>. The Profiler shows Card rendering on every keystroke. Why does memo not help, and what is the cheapest fix?
Show answer
The children prop is <Icon name="doc" />, a new element object on every parent render, so the shallow comparison sees a changed prop and memo never skips. The cheapest fix is to move the search box state into its own component so the parent stops re-rendering on each keystroke. Hoisting the <Icon> element to module level would also work. Wrapping the element in useMemo works too but adds more code than the other fixes.
Exercise
You wrote const label = useMemo(() => first + ' ' + last, [first, last]); and then pass label to a plain <h1>. Should you keep the useMemo? Give two reasons.
Show answer
No. Joining two short strings is far cheaper than the hook's dependency comparison and cache bookkeeping. The result is a string, which Object.is already treats as equal when the content matches, so no stable reference is needed. <h1> is also a DOM element that compares nothing. Replace it with const label = first + ' ' + last;.