Sub topic 2
Why Inline Objects and Functions Break `memo`
Assume you know function components, JSX, props, hooks, and JavaScript reference values. This chapter focuses on why memoization fails when props receive new objects or functions during every render.
Inline values have new references
React.memo compares each prop with Object.is. Primitive values such as strings and numbers compare by value. Objects, arrays, and functions compare by reference.
<Chart options={{ color: 'blue' }} />The object contains the same data each time, but the object itself is new each time the parent renders. A memoized Chart therefore receives a changed prop and renders again. The same problem occurs with inline functions:
<Row onSelect={(id) => select(id)} />The function is recreated on every render.
Dependency arrays and `Object.is`
Hooks such as useMemo and useCallback accept a dependency array. React compares each dependency with its previous value using Object.is.
If any dependency changes, React recalculates the value or function. If none changes, React can reuse the previous result.
Cache values with `useMemo`
Use useMemo when a calculation is expensive or when an object or array prop must keep a stable reference.
const options = useMemo(() => ({ color: 'blue' }), []);
const visible = useMemo(
() => products.filter((product) => product.name.includes(query)),
[products, query]
);The empty array means options is created once for the component instance. The filtered list is recalculated when products or query changes.
Keep function props stable with `useCallback`
useCallback returns the same function reference until one of its dependencies changes.
const Row = memo(function Row({ item, onSelect }) {
return <li onClick={() => onSelect(item.id)}>{item.name}</li>;
});
function List({ items }) {
const [selectedId, setSelectedId] = useState(null);
const handleSelect = useCallback((id) => {
setSelectedId(id);
}, []);
return items.map((item) => (
<Row key={item.id} item={item} onSelect={handleSelect} />
));
}The empty dependency array is correct because the callback does not read changing values. Include every changing value that the callback reads.
Exercise
Why can an inline object cause a memoized child to render again?
Show answer
Each parent render creates a new object reference, so React.memo detects a changed prop with Object.is.