Sub topic 9
Memoizing with React.memo, useMemo, and useCallback
This chapter assumes you can write function components with props, state, and hooks. You should also know how to record a session in the React DevTools Profiler and read its "why did this render?" output. Memoization is the fix to try after you have measured a real problem and moved state down as far as it will go.
What memoization does
Memoization means caching a result and reusing it while the inputs stay the same. React offers three tools for this.
| Tool | What it caches | Reuses the cache when |
|---|---|---|
| `memo` | A component's rendered output | All props are shallowly equal to last time |
| `useMemo` | A computed value | Every dependency is unchanged |
| `useCallback` | A function | Every dependency is unchanged |
Shallow equality compares with Object.is. Two primitives match if they are equal. Two objects, arrays, or functions match only if they are the same reference.
React.memo and stable props
By default, a parent render re-renders all of its children. memo wraps a component so React skips it when its props have not changed.
A new function is created on every render. Passing an inline function to a memoized child breaks the memoization, because the prop is a new reference each time. useCallback returns the same function until its dependencies change.
import { memo, useCallback, useState } from "react";
const Row = memo(function Row({ item, onSelect }) {
return <li onClick={() => onSelect(item.id)}>{item.name}</li>;
});
export function List({ items }) {
const [selectedId, setSelectedId] = useState(null);
// Stable function identity lets memo(Row) skip re-rendering when only selectedId changes.
const handleSelect = useCallback((id) => setSelectedId(id), []);
return (
<>
<p>Selected: {selectedId}</p>
<ul>
{items.map((item) => (
<Row key={item.id} item={item} onSelect={handleSelect} />
))}
</ul>
</>
);
}setSelectedId is stable, so the empty dependency array is correct here. Without useCallback, every click would re-render every Row. Without memo, useCallback would do nothing useful, because the children would re-render anyway. The two work as a pair.
useMemo for expensive calculations
useMemo caches a value. Use it when a calculation is slow and the component re-renders for reasons that do not affect the result.
import { useMemo, useState } from "react";
export function FilteredList({ items }) {
const [filter, setFilter] = useState("");
const [dark, setDark] = useState(false);
// Recomputed only when items or filter change, not when dark toggles.
const visible = useMemo(
() => items.filter((item) => item.name.toLowerCase().includes(filter.toLowerCase())),
[items, filter]
);
return (
<div className={dark ? "dark" : "light"}>
<button onClick={() => setDark((d) => !d)}>Toggle theme</button>
<input value={filter} onChange={(e) => setFilter(e.target.value)} />
<ul>
{visible.map((item) => (
<li key={item.id}>{item.name}</li>
))}
</ul>
</div>
);
}Toggling the theme re-renders the component, but visible is reused. The same idea applies to objects and arrays you pass as props to a memoized child. Wrapping them in useMemo keeps their reference stable.
How to decide
Common errors
- Memoizing the child but not the props. An inline
onClick={() => ...},style={{...}}, oritems={data.filter(...)}creates a new reference every render. The profiler will still report "props changed". - Wrong dependency arrays. Omitting a value the callback reads gives you stale data. Fix the array rather than silencing the lint rule.
- Memoizing everything. Each cache costs memory and a comparison. For cheap components the check can cost about as much as the render it avoids.
- Trusting development timings. Confirm the gain in a production build.
Exercise
A memoized Row still re-renders on every parent render. The parent passes onSelect={(id) => setSelectedId(id)}. The Profiler says "props changed". What is the cause and the fix?
Show answer
The inline arrow function is a new reference on each render, so the shallow comparison fails. Define the handler with useCallback((id) => setSelectedId(id), []) and pass that. Then record again to confirm that Row no longer renders.