Sub topic 13
Fixing unnecessary renders with memo and useCallback
This chapter assumes you can write function components, use useState and props, and have already recorded a Profiler session and read its "Why did this render?" reasons. Here you act on what the Profiler reported.
The problem the Profiler shows
memo wraps a component so React skips re-rendering it when its props are shallowly equal to the previous props. Shallow equality compares each prop with Object.is. Strings and numbers pass. A function created inline fails, because every render creates a new function object.
This list re-renders every Item on each selection, even though memo is applied:
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>
);
}Record a session, click one item, and stop. Select an Item in the flamegraph. The Profiler reports that a prop changed, and the changed prop is onSelect. The label prop is the same string as before.
Fix it with useCallback
useCallback returns the same function object across renders as long as its dependency array does not change. Here the handler only calls setSelected, which React guarantees is stable, so the dependency array is empty.
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>
);
}Both pieces are required. useCallback without memo on the child does nothing useful, because the child re-renders whenever its parent does. memo without a stable prop does nothing either, as the first example shows.
Confirm the fix
Profile again with the same interaction.
- Start recording and click one item.
- Stop recording and open the flamegraph for the commit.
- Look at the
Itemcomponents. Those that did not re-render are drawn in gray. - Select one gray
Item. The Profiler says the component did not render during this commit.
The List component still renders, because its state changed. Only the Item instances whose props changed render with it. Now the commit should be much cheaper, and the ranked chart should list fewer components.
Common mistakes
- Unstable object or array props.
style={{ color: 'red' }}oritems={[1, 2]}creates a new reference on every render. Move constants outside the component or wrap derived values inuseMemo. - Wrong dependencies. If the callback reads state or props, list them. An empty array with a stale value gives bugs that are harder to find than the extra render.
- Memoizing everything. Comparing props has a cost. Add
memoonly where the Profiler shows a slow or frequent render.
Exercise
You wrapped a child in memo and passed it config={{ mode: 'dark' }} from its parent. The Profiler still shows the child rendering on every parent update, with "props changed: config". Why does this happen, and how would you fix it?
Show answer
The object literal is a new object on every parent render, so the shallow comparison sees a different config reference even though its contents are the same. Fix it by defining the object outside the component if it is constant, or by creating it with useMemo using the values it depends on. Then profile again to confirm the child is skipped.