Sub topic 10
Skipping work with React.memo, useMemo, and useCallback
This chapter assumes you know how components, props, and useState work. It also assumes you know that a state change makes React re-render a component and, by default, all of its children. Earlier chapters covered the render phase and reconciliation. Here you will see how to skip some of that work, and when it is worth doing.
Why re-renders cascade
When a component re-renders, React calls it again and also calls every child component it returns. This happens even if a child's props did not change. Most of the time this is fast, and the reconciler only touches the DOM where output differs.
Memoization means remembering a previous result and reusing it when the inputs are the same. React offers three tools for this.
| Tool | What it remembers | Skips |
|---|---|---|
| `React.memo` | The last rendered output of a component | Calling the component again |
| `useMemo` | The result of a calculation | Running the calculation again |
| `useCallback` | A function object | Creating a new function identity |
React.memo
memo wraps a component. Before rendering it, React compares the new props to the old props one by one with Object.is. This is a shallow comparison. If every prop is equal, React reuses the previous result and does not call the component.
A re-render of the parent still happens. memo only stops the cascade at the child.
The identity problem
Objects, arrays, and functions are created fresh on every render. Two functions with the same code are still different values. So a memoized child that receives an inline function sees a changed prop every time, and memo does nothing.
useCallback returns the same function between renders as long as its dependency array has not changed. useMemo does the same for any value, such as an object or the result of a filter.
Worked example
import { memo, useCallback, useState } from 'react';
const Row = memo(function Row({ id, onSelect }) {
console.log('Row rendered', id);
return <li onClick={() => onSelect(id)}>Row {id}</li>;
});
function List({ ids }) {
const [selected, setSelected] = useState(null);
const handleSelect = useCallback(id => setSelected(id), []);
return (
<>
<p>Selected: {String(selected)}</p>
<ul>
{ids.map(id => (
<Row key={id} id={id} onSelect={handleSelect} />
))}
</ul>
</>
);
}Clicking a row calls setSelected, so List re-renders. Each Row receives the same id and the same handleSelect, so memo skips them. The empty dependency array is safe here because setSelected is stable and the callback reads no other values.
Common errors
- Memoizing the child but not its props. An inline
onSelect={() => ...}orstyle={{ ... }}creates a new value each render and defeatsmemo. - Wrong dependency arrays. If
useCallbackoruseMemoomits a value it reads, the function sees stale data. Include every reactive value it uses. - Memoizing everything. Each hook costs memory and a comparison. For cheap components, the check can cost more than the render.
- Relying on memo for correctness. React may discard cached values. Your code must work correctly without them, so use memoization only as a performance hint.
- Children passed to a memoized component. JSX such as
<Row><b>hi</b></Row>creates a newchildrenelement every render, which also breaks the shallow comparison.
When it is worth it
Apply memoization when a component is expensive to render, re-renders often with unchanged props, and sits under a parent that updates frequently. Often a structural fix is simpler. Moving state down into a smaller component, or passing JSX as children, avoids the re-render without any hooks.
Exercise
A memoized Row still re-renders every time its parent renders. The parent passes onSelect={id => setSelected(id)} written inline. Why does this happen, and how do you fix it?
Show answer
The inline arrow function is a new function object on every parent render, so the shallow Object.is prop comparison finds onSelect changed and memo cannot skip the render. Wrap the handler in useCallback with the right dependencies (here an empty array is enough, since setSelected is stable) and pass that stable function to Row.
Exercise
Why can wrapping every component in memo make an app slower?
Show answer
Each memoized component pays for a prop comparison on every parent render. If the component is cheap or its props change nearly every time, the comparison costs more than it saves, and the extra cached values use memory.