Sub topic 13
Fixing unnecessary renders with memo and useCallback
This chapter assumes you can write function components, use useState and props, and record a Profiler session as described in the earlier chapters. You should also know how to turn on "Record why each component rendered while profiling" in the Profiler settings.
By the end you will be able to take a Profiler finding such as "Props changed: onSelect" and turn it into a fix. You will also be able to check with a second recording that the fix worked.
Why a parent render causes child renders
When a component's state changes, React re-renders that component. By default it then re-renders every child component below it, whether or not the child's props changed. Most of the time this is cheap and you should leave it alone.
It becomes a problem when a child is expensive to render, or when the same child is rendered hundreds of times in a list. In that case, work React repeats for no visible change can make typing or clicking feel slow.
React.memo changes the default. It wraps a component so that React skips re-rendering it when its props are the same as last time. "Same" means a shallow comparison with Object.is on each prop, which has two consequences:
- Primitives such as strings, numbers, and booleans compare by value.
- Objects, arrays, and functions compare by reference. A new object with identical contents counts as a changed prop.
The second point causes most "memo does nothing" bugs.
Step 1: Reproduce the problem and read the Profiler
Here is a list where every item re-renders when you select one, even though only the Selected: text should change.
import { memo, useState } from 'react';
const Item = memo(function Item({ label, onSelect }) {
return <li onClick={() => onSelect(label)}>{label}</li>;
});
export function List({ items }) {
const [selected, setSelected] = useState(null);
return (
<div>
<p>Selected: {selected ?? 'none'}</p>
<ul>
{items.map((label) => (
<Item
key={label}
label={label}
onSelect={(value) => setSelected(value)}
/>
))}
</ul>
</div>
);
}Item is already wrapped in memo, so it looks protected. Record a session in the Profiler, click one item, and stop recording. Then work through these checks:
- Select the commit caused by your click in the commit bar.
- In the flamegraph, check whether the
Itembars are colored. Colored bars rendered in this commit. Gray bars did not. - Click one
Itembar. The right-hand pane lists the render reason, for exampleProps changed: onSelect. - Note that
labelis not in the list. Only the function prop changed.
The cause is that (value) => setSelected(value) is created fresh every time List renders. Each Item receives a different function reference, so memo sees a changed prop and renders the component again. The memo wrapper is working correctly here. The props really are different as far as Object.is is concerned.
Step 2: Stabilize the function with useCallback
useCallback returns the same function reference between renders as long as its dependency array has not changed. Here is the corrected list.
import { memo, useCallback, useState } from 'react';
const Item = memo(function Item({ label, onSelect }) {
return <li onClick={() => onSelect(label)}>{label}</li>;
});
export function List({ items }) {
const [selected, setSelected] = useState(null);
const handleSelect = useCallback((value) => setSelected(value), []);
return (
<div>
<p>Selected: {selected ?? 'none'}</p>
<ul>
{items.map((label) => (
<Item key={label} label={label} onSelect={handleSelect} />
))}
</ul>
</div>
);
}The dependency array is empty because the callback only uses setSelected. React guarantees that state setter functions keep the same identity for the lifetime of the component. If the callback read selected or any other prop or state value, that value would have to be in the array. Otherwise the callback would use a stale value from an earlier render.
The inline onClick={() => onSelect(label)} inside Item does not need fixing. It is attached to a DOM element (li), not to a memoized component, so nothing compares it.
Step 3: Verify with a second recording
Do not assume the fix worked. Repeat the exact same interaction under the Profiler and compare:
- The commit for the click should now show only
Listas rendered. TheItembars should be gray. - In the Components tab, memoized components carry a
Memobadge. If you do not see it, you may be looking at a different component than you wrapped. - If you hover a gray bar, the tooltip says the component did not render during this commit.
The ranked chart is useful here. Before the fix it listed every Item with similar render times. After the fix it should list only the components that really rendered.
Choosing between useCallback, useMemo, and other fixes
The Profiler's render reason tells you which tool to use.
| Render reason shown | Likely cause | Fix |
|---|---|---|
| Props changed: a function prop | Inline function recreated on each parent render | `useCallback` in the parent |
| Props changed: an object or array prop | Inline `{}` or `[]`, or a derived value created during render | `useMemo` in the parent, or move the constant outside the component |
| Props changed: `children` | JSX passed as children is recreated on each render | Restructure so the changing state lives lower in the tree |
| Hooks changed | The component's own state or a hook it uses changed | Usually a real update. Check whether the state needs to exist |
| Context changed | A context value changed | Split the context, or memoize the provider's `value` |
| The parent rendered | No props changed, but the component is not memoized | Wrap it in `memo`, if it is expensive enough to matter |
For an object prop, the pattern looks like this:
import { memo, useMemo } from 'react';
const Chart = memo(function Chart({ options }) {
return <pre>{JSON.stringify(options)}</pre>;
});
export function Dashboard({ theme }) {
const options = useMemo(() => ({ theme, animate: false }), [theme]);
return <Chart options={options} />;
}Here options keeps its identity until theme changes, so Chart re-renders only when it needs to.
Sometimes the better fix is to avoid the render instead of memoizing it. If a piece of state is used by only one small component, move the state into that component. Then its parent and siblings never re-render when it changes. This costs nothing at runtime and has no dependency arrays to maintain.
Common errors
memo plus an unstable prop
This is the case from Step 1. Wrapping a component in memo while passing it a new function, object, or array on every render gives you the comparison cost with none of the savings. Read the render reason before adding useCallback or useMemo, so you know which prop to stabilize.
Wrong or missing dependencies
An incorrect dependency array causes stale-closure bugs: the callback keeps using old values. Use the react-hooks/exhaustive-deps ESLint rule and treat its warnings as bugs. If a callback needs the latest state, use the functional form of the setter, such as setCount((c) => c + 1), so you can keep the array empty without going stale.
Memoizing everything
Each memo call adds a props comparison on every parent render, and each useCallback adds a dependency check. For a cheap component that usually re-renders anyway, this is a net loss and adds code to read. Memoize where the Profiler shows a real cost, such as long render times or many repeated renders.
Profiling a development build and trusting the numbers
Development builds are slower and include extra checks, so absolute times are inflated. Use the numbers to compare before and after. For final confirmation, use a production profiling build, as covered in the build modes chapter.
Expecting memo to stop state-driven renders
memo only guards against re-renders caused by a parent. If a component's own state, a hook it uses, or a context it reads changes, it renders regardless. In the Profiler this appears as Hooks changed or Context changed, not as a props reason.
A quick checklist
- Record the interaction in the Profiler with render reasons enabled.
- Find the components that rendered but should not have.
- Read the reason. If it is a changed prop, identify which one.
- Stabilize that prop in the parent, or move the state down so the parent stops re-rendering.
- Make sure the child is wrapped in
memo. - Record again and confirm the child is gray.
Exercise
A memoized Row component still re-renders every time its parent renders. The Profiler says Props changed: style. The parent passes style={{ color: 'red' }}. Give two ways to fix it, and say which one you would pick.
Show answer
Move the object outside the component as a constant (const rowStyle = { color: 'red' };), or create it with useMemo(() => ({ color: 'red' }), []) inside the parent. Because the value never depends on props or state, the module-level constant is better. It needs no hook, no dependency array, and no per-render work. Then record again to confirm that Row is gray.
Exercise
You wrapped a child in memo and the parent passes onSave={useCallback(() => save(draft), [])}, where draft is a state variable. The child no longer re-renders, but saving sends old text. What is wrong, and how do you fix it?
Show answer
The empty dependency array makes the callback capture the first value of draft forever (a stale closure). Add draft to the dependency array: useCallback(() => save(draft), [draft]). The child will then re-render whenever draft changes, which is correct because its behavior depends on it. Alternatively, keep draft in a ref that the callback reads, if you need a stable function.