Sub topic 10
Skipping Work with React.memo, useMemo, and useCallback
This chapter assumes you know how to write function components with props and useState, and that you have read the earlier chapters on what triggers a re-render and how the render and commit phases work. Here you will learn the three tools React gives you to skip work, how each one decides whether to skip, and when using them is worth the cost.
The default: a parent render re-renders its children
When a component renders, React calls it, gets back a tree of elements, and then renders every child component in that tree. It does this even if a child's props did not change. React does not compare props by default.
This is usually fine. Rendering is a calculation, and most components are cheap to call. The commit phase still only touches the DOM nodes that differ. A re-render that produces the same output costs some JavaScript time but changes nothing on screen.
Skipping a render matters only when a component is slow to render, or when a large number of components re-render for no reason. The tools below let you opt in to skipping.
React.memo: skip a component when props are equal
memo wraps a component. Before re-rendering it because its parent rendered, React compares the new props to the previous props with Object.is on each prop (a shallow comparison). If every prop is the same, React reuses the previous result and does not call the component.
import { memo, useState } from 'react';
const Label = memo(function Label({ text }) {
console.log('Label rendered');
return <p>{text}</p>;
});
function Page() {
const [count, setCount] = useState(0);
return (
<>
<button onClick={() => setCount(count + 1)}>Clicked {count}</button>
<Label text="Static text" />
</>
);
}Each click re-renders Page. Label receives the string "Static text" every time, and Object.is("Static text", "Static text") is true, so Label does not render again.
What shallow comparison means
Object.is compares primitives by value and objects, arrays, and functions by reference. Two objects with identical contents are still different if they were created separately.
| Prop value on two renders | `Object.is` result | `memo` skips? |
|---|---|---|
| `"a"` and `"a"` | true | Yes |
| `5` and `5` | true | Yes |
| `{ x: 1 }` and a new `{ x: 1 }` | false | No |
| `[1, 2]` and a new `[1, 2]` | false | No |
| `() => {}` and a new `() => {}` | false | No |
| The same object reference twice | true | Yes |
This is the most common reason memo appears not to work. A parent that writes <Row style={{ color: 'red' }} /> or <Row onSelect={() => ...} /> creates a new object or function on every render, so the comparison always fails.
What memo does not stop
memo only skips re-renders caused by the parent. It does not stop a component from re-rendering when:
- its own state changes,
- a context it reads with
useContextchanges, - a hook inside it, such as a custom hook with its own state, triggers an update.
useCallback: keep a function the same between renders
A function declared inside a component is a new function object on every render. useCallback returns the same function object as long as its dependency array is unchanged.
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>
</>
);
}Selecting a row changes selected, so List re-renders. Each Row receives the same id and the same handleSelect function, so memo skips all of them. Without useCallback, handleSelect would be a new function each time and every row would re-render.
The empty dependency array is safe here because setSelected is stable and the callback reads nothing else from the render. If the callback read a prop or state value, that value would have to be listed in the array. Otherwise the callback would keep using the value from the render in which it was created.
useCallback on its own does nothing useful. It only helps when the function is passed to a memo component, or used as a dependency of another hook.
useMemo: keep a calculated value
useMemo runs a function during render and caches its result. On later renders, React returns the cached value unless a dependency changed.
import { useMemo, useState } from 'react';
function Products({ products }) {
const [query, setQuery] = useState('');
const [dark, setDark] = useState(false);
const visible = useMemo(
() => products.filter(p => p.name.toLowerCase().includes(query.toLowerCase())),
[products, query]
);
return (
<div className={dark ? 'dark' : 'light'}>
<input value={query} onChange={e => setQuery(e.target.value)} />
<button onClick={() => setDark(!dark)}>Toggle theme</button>
<ul>
{visible.map(p => <li key={p.id}>{p.name}</li>)}
</ul>
</div>
);
}Toggling the theme re-renders Products, but products and query are unchanged, so the filter does not run again.
useMemo has two uses:
- Skipping an expensive calculation. Measure first. Filtering a few hundred items is usually far below one millisecond.
- Keeping an object or array reference stable so that it can be passed to a
memocomponent or used in another hook's dependency array.
useCallback(fn, deps) is the same as useMemo(() => fn, deps). It is a shorter way to write the function case.
How the three fit together
useCallback and useMemo exist mainly to make the right-hand check come out as "equal". memo is the part that actually skips the render.
Common errors
- Memoizing the child but not its props.
memo(Row)with an inline arrow function prop never skips. Stabilize the function withuseCallback, or move it out of the component if it uses no render values. - Missing dependencies. Leaving out a value that the callback or calculation reads gives you stale results. Use the
react-hooks/exhaustive-depslint rule and do not silence it. - Passing
childrento a memoized component. Thechildrenprop is a React element created by the parent on every render, so it is a new object each time.memowill not skip in that case unless the element itself is memoized. - Treating memoization as a guarantee. React may discard cached values in some situations, such as during development edits. Your code must still be correct if the calculation runs again.
- Mutating props or state. A shallow comparison cannot see a mutation. If you push into an array and pass the same array reference, a memoized child will not update. Create a new array instead.
- Memoizing everything. Each
memo,useMemo, anduseCallbackcosts memory and a comparison on every render. When the comparison usually fails, you pay for it and gain nothing.
Alternatives that skip work without memoization
Before adding hooks, check whether the structure can change.
- Move state down. If only a small part of the tree uses a piece of state, put that state in a smaller component. The rest of the tree no longer re-renders when it changes.
- Lift content up with children. A component that holds state and receives
childrenfrom a parent does not re-render those children when its own state changes, because the same element objects are passed in again.
import { useState } from 'react';
function ColorPicker({ children }) {
const [color, setColor] = useState('red');
return (
<div style={{ color }}>
<input value={color} onChange={e => setColor(e.target.value)} />
{children}
</div>
);
}
function App() {
return (
<ColorPicker>
<ExpensiveTree />
</ColorPicker>
);
}When color changes, ColorPicker re-renders. ExpensiveTree is an element created by App, which did not re-render, so React sees the identical element object and reuses it.
When to apply them
Use this order of decisions:
- Is there a visible slowness? Measure it with the React DevTools Profiler (covered in a later chapter) before changing anything.
- Can you move state down or pass content as
children? Do that first. - Is one component slow and rendered often with unchanged props? Wrap it in
memo, then stabilize each object or function prop it receives. - Is a calculation slow? Wrap it in
useMemowith correct dependencies.
Apply memoization where the Profiler shows a measurable gain. In other places, leave the code plain.
Exercise
A memo-wrapped Chart component receives options={{ type: 'bar' }} from its parent, and it still re-renders every time the parent renders. Why does this happen, and how can you fix it?
Show answer
The object literal { type: 'bar' } is created again on every parent render, so Object.is sees a different reference and memo cannot skip. Either define the object outside the component (if it is constant), or create it once with useMemo(() => ({ type: 'bar' }), []) and pass that value.
Exercise
In the List example, handleSelect is changed to useCallback(id => setSelected(id === selected ? null : id), []). What goes wrong, and what is the fix?
Show answer
The callback reads selected but does not list it in the dependency array, so it always sees the value from the first render and toggling behaves incorrectly. Either add selected to the dependencies (which creates a new function when selected changes, so rows re-render) or use the updater form: setSelected(current => (current === id ? null : id)), which keeps the empty dependency array correct.