Sub topic 5
Why inline objects and functions break memo
This chapter assumes you know function components, JSX, useState, and how props and children pass between components. It also assumes you know that JavaScript objects, arrays, and functions are reference values. Earlier chapters covered why components re-render, referential equality, and the shallow prop comparison that React.memo performs. Here you will see where that comparison fails in practice and how to repair it.
The problem in one sentence
React.memo compares each prop with Object.is. An object, array, or function written inline in JSX is created again on every render of the parent, so it is a new reference each time. The comparison reports a change, and the memoized child renders anyway.
What "unstable" means
A prop is stable if its reference stays the same between renders when its meaning has not changed. A prop is unstable if its reference changes even though the contents are identical.
const a = { color: 'blue' };
const b = { color: 'blue' };
console.log(Object.is(a, a)); // true
console.log(Object.is(a, b)); // falsePrimitives (strings, numbers, booleans) compare by value, so they are always stable when the value is unchanged. Objects, arrays, and functions compare by identity. Each time a component function runs, every literal in its body is evaluated again and produces a fresh identity.
The three usual offenders
| Inline value | Example | Why it is new each render |
|---|---|---|
| Object literal | `style={{ margin: 8 }}` | `{}` allocates a new object |
| Array literal | `tags={['a', 'b']}` | `[]` allocates a new array |
| Function | `onSelect={() => go(id)}` | Arrow functions are created when the expression runs |
Other sources are less obvious. Calling .filter(), .map(), or .sort() on a copy in the parent body returns a new array. Spreading props, as in {...rest}, does not create a new prop value on its own, but building { ...a, ...b } and passing it does. A default value such as function Row({ options = {} }) creates a new {} on every render in which the prop is missing.
A demonstration of the failure
The component below is memoized, but its parent passes an inline object. Clicking the button changes count, which has nothing to do with Chart, yet Chart renders every time.
import { memo, useState } from 'react';
const Chart = memo(function Chart({ options }) {
console.log('render chart');
return <div>{options.color}</div>;
});
export function Dashboard() {
const [count, setCount] = useState(0);
return (
<>
<button onClick={() => setCount(count + 1)}>Clicked {count}</button>
<Chart options={{ color: 'blue' }} />
</>
);
}Each click re-runs Dashboard. The expression { color: 'blue' } runs again, Object.is(prevOptions, nextOptions) is false, and memo lets Chart render. The memo wrapper still does its comparison work, so this code is slightly slower than having no memo at all.
With an inline literal, the flow always leaves through the "No" branch.
Fixing unstable objects and arrays
There are three fixes, ordered here from simplest to most flexible.
- Move the value out of the component if it never depends on props or state. A module-level constant is created once.
- Memoize it with
useMemoif it depends on props or state. - Pass primitives instead. If
Chartonly needs a color, passcolor="blue".
The first fix needs no hook:
const CHART_OPTIONS = { color: 'blue' };
export function Dashboard() {
// ...
return <Chart options={CHART_OPTIONS} />;
}When the value depends on something in the component, use useMemo. It returns the same reference until a dependency changes:
import { memo, useMemo, useState } from 'react';
const Chart = memo(function Chart({ options }) {
console.log('render chart');
return <div>{options.color}</div>;
});
export function Dashboard() {
const [count, setCount] = useState(0);
// Broken: a new object on every render, so memo sees a changed prop.
// <Chart options={{ color: 'blue' }} />
// Fixed: the same object is reused until its dependencies change.
const options = useMemo(() => ({ color: 'blue' }), []);
return (
<>
<button onClick={() => setCount(count + 1)}>Clicked {count}</button>
<Chart options={options} />
</>
);
}The empty dependency array means the object is built once. If it depended on a prop such as theme, you would write useMemo(() => ({ color: theme.accent }), [theme.accent]). Listing theme.accent rather than theme is deliberate: depending on a primitive avoids invalidating the cache when the parent passes a new theme object with the same accent.
Fixing unstable functions
Functions are the most common cause of broken memoization, because event handlers are written inline by habit. useCallback returns the same function reference until its dependencies change.
import { memo, useCallback, useState } from 'react';
const Row = memo(function Row({ item, onSelect }) {
console.log('render row', item.id);
return <li onClick={() => onSelect(item.id)}>{item.name}</li>;
});
export function List({ items }) {
const [selectedId, setSelectedId] = useState(null);
const handleSelect = useCallback((id) => {
setSelectedId(id);
}, []);
return (
<>
<p>Selected: {selectedId ?? 'none'}</p>
<ul>
{items.map((item) => (
<Row key={item.id} item={item} onSelect={handleSelect} />
))}
</ul>
</>
);
}Selecting a row calls setSelectedId, so List re-renders. Each Row receives the same item reference and the same handleSelect, so memo skips them.
Two details matter here:
- The
onClickinsideRowis still an inline arrow. That is fine. It is passed to a DOM element (li), not to a memoized component, so nothing compares it. handleSelecttakes the id as an argument instead of closing over it. A single shared handler works for every row. If the parent wroteonSelect={() => handleSelect(item.id)}insidemap, each row would get a new function andmemowould fail again.
The updater form keeps the dependency array short
handleSelect has an empty dependency array because setSelectedId is guaranteed stable by React. If the handler needed the current state, you would have two choices. You could add the state to the dependencies, which changes the function whenever the state changes. Or you could use the functional update form, which needs no dependency:
const toggleDark = useCallback(() => {
setDarkMode((d) => !d);
}, []);Prefer the functional form when you can. It keeps the function stable for the lifetime of the component.
Chain reactions: one unstable prop is enough
memo skips a render only if every prop is equal. Suppose a component receives five props and four are stable. One inline function still forces a render. When you memoize a component, audit all of its props, not only the one you suspect.
The same applies to dependency arrays. If useMemo or useCallback depends on an unstable value, the hook recomputes every render and returns a new reference. Memoization then does nothing, and the chain breaks further down:
function Parent({ filters }) {
// `filters` is a new object each render if the grandparent writes it inline,
// so this useMemo recomputes every time.
const query = useMemo(() => buildQuery(filters), [filters]);
return <Results query={query} />;
}The fix belongs where the unstable value is created, in the grandparent. Stabilizing only the middle layer does not help.
Children are props too
children is a prop. JSX such as <Card><p>Hello</p></Card> creates a new element object on each parent render, so a memoized Card that receives JSX children always re-renders. This surprises people who wrap a component in memo and see no effect. Either memoize the element with useMemo, or stop relying on memo and restructure so the parent does not re-render, which is covered in the chapter on moving state down.
Common mistakes
- Wrapping the child in
memobut not stabilizing the props. This is the failure in this chapter. The wrapper adds cost and gains nothing. - Stabilizing props but forgetting to wrap the child in
memo.useCallbackalone does not prevent a child from rendering. The child still re-renders when its parent does. The hook only helps when something downstream compares the reference: amemocomponent, or another hook's dependency array. - Wrong dependencies. If
useCallbackomits a value it reads, the function keeps using an old copy of that value (a stale closure). Follow the exhaustive-deps lint rule fromeslint-plugin-react-hooksrather than silencing it. - Memoizing everything. Each
useMemoanduseCallbackcosts a dependency comparison and keeps the previous value in memory. Use them where a memoized child or an expensive computation justifies them.
Check that it worked
Do not assume a fix works. Add a console.log as in the examples above, or open the React DevTools Profiler and enable "Record why each component rendered". For a memoized component, the Profiler shows a prop whose reference changed, such as "Props changed: options". If the child still renders after your fix, that message names the prop that is still unstable.
Exercise
A memoized component Avatar receives size="large" and style={{ borderRadius: 4 }}. The parent re-renders when unrelated state changes, and Avatar re-renders each time. Which prop is the cause, and what is the simplest fix?
Show answer
The style prop is the cause. The inline object is a new reference on each render, so memo sees a change. The size string is a primitive and compares equal. The simplest fix is to move the style object to a module-level constant, for example const AVATAR_STYLE = { borderRadius: 4 };, and pass style={AVATAR_STYLE}. Use useMemo only if the object depends on props or state.
Exercise
A parent renders items.map((item) => <Row key={item.id} item={item} onSelect={() => onPick(item.id)} />), and Row is wrapped in memo. Rewrite it so memo can skip rows whose item has not changed.
Show answer
Pass a single stable handler and let the row supply the id. In the parent, create const handlePick = useCallback((id) => { onPick(id); }, [onPick]); and render <Row key={item.id} item={item} onSelect={handlePick} />. Inside Row, call onSelect(item.id) from its click handler. This works only if onPick itself is stable, so the component that owns onPick may need useCallback as well.
Exercise
You wrapped a function in useCallback and passed it to a child that is not wrapped in memo. The child still renders on every parent render. Why?
Show answer
Without memo, a child re-renders whenever its parent re-renders, whatever its props are. useCallback only gives the function a stable reference. Something has to compare that reference, either memo on the child or a dependency array in a hook. Wrapping the child in memo fixes it, provided its other props are stable too.