Sub topic 5
Why inline objects and functions break memo
This chapter assumes you know function components, useState, props, and that JavaScript objects, arrays and functions are reference values. It builds on React.memo and referential equality from earlier chapters.
The problem in one sentence
memo compares each prop with Object.is. An object, array or function written inline in JSX is created again on every render, so it is never the same reference as last time. The prop always looks changed, and memo never skips.
A memoized child that still re-renders
import { memo, useState } from 'react';
const Chart = memo(function Chart({ options, onZoom }) {
console.log('render chart');
return <div onClick={onZoom}>{options.color}</div>;
});
export function Dashboard() {
const [count, setCount] = useState(0);
return (
<>
<button onClick={() => setCount(count + 1)}>Clicked {count}</button>
<Chart options={{ color: 'blue' }} onZoom={() => console.log('zoom')} />
</>
);
}Each click re-renders Dashboard. That creates a new { color: 'blue' } and a new arrow function. Object.is returns false for both, so Chart renders every time even though nothing visible changed.
Fix objects and arrays with useMemo
useMemo returns the same reference until its dependencies change.
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);
const options = useMemo(() => ({ color: 'blue' }), []);
return (
<>
<button onClick={() => setCount(count + 1)}>Clicked {count}</button>
<Chart options={options} />
</>
);
}With an empty dependency array, options is created once. Clicking the button no longer logs render chart.
Fix functions with useCallback
useCallback(fn, deps) keeps the same function reference until deps 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>
</>
);
}handleSelect uses only setSelectedId, which React guarantees is stable, so an empty array is correct. Selecting a row updates List, but rows whose item is unchanged are skipped. The onClick arrow inside Row is fine, because it is attached to a DOM element and not passed to a memoized component.
Common mistakes
| Mistake | Why it fails | Fix |
|---|---|---|
| Memoizing the child but passing `style={{ ... }}` | New object each render | Move it outside the component, or use `useMemo` |
| Wrapping the child in `memo` but not stabilizing a callback | New function each render | `useCallback` |
| Stabilizing one prop out of three | One changed prop is enough to re-render | Check every prop |
| Dependency array lists a value that changes each render | The cache is rebuilt each time | Stabilize that dependency first |
| Passing `children` as inline JSX to a memoized component | `children` is a new element object each render | Avoid memo there, or lift the JSX out |
A constant that does not depend on props or state needs no hook. Define it at module level and it keeps one reference for the life of the app:
const chartOptions = { color: 'blue' };Finding the unstable prop
If a memoized component keeps re-rendering, check each prop and ask whether it is created during render. Object literals, array literals, arrow functions, and results of .map() or .filter() are the usual causes. The Profiler's "Why did this render?" option, if enabled, names the props that changed.
Exercise
A memoized Avatar receives size={48}, user={user} and style={{ borderRadius: '50%' }}. It re-renders every time the parent does, although user comes from state and does not change. Which prop is the cause, and what are two ways to fix it?
Show answer
The style prop. The literal { borderRadius: '50%' } is a new object on every render, so Object.is reports a change. size is a number and user keeps its reference, so both compare equal. Fix it by moving the object to a module-level constant, or by creating it with useMemo(() => ({ borderRadius: '50%' }), []).
Exercise
Why is useCallback useless for a handler passed to a plain <button> inside a component that is not wrapped in memo?
Show answer
A DOM element does not use memo to skip work, and the parent re-renders anyway. The stable reference is never compared, so the hook only adds overhead.