React ยท Chapter 17 of 42
useMemo Hook
`useMemo` memoizes the result of an expensive calculation, recomputing it only when its dependencies change. This avoids unnecessary recalculation on every render.
Use it sparingly โ only when a computation is genuinely expensive and causing measurable performance issues.
How it works
`useMemo(() => computeValue(a, b), [a, b])` returns the cached result unless `a` or `b` change.
When to use it
Reach for useMemo when profiling shows a calculation (like filtering a huge list) is genuinely slow and recomputed too often.
Example 1 (jsx)
import { useMemo } from "react";
function ExpensiveList({ items, filter }) {
const filtered = useMemo(
() => items.filter(i => i.includes(filter)),
[items, filter]
);
return <ul>{filtered.map(i => <li key={i}>{i}</li>)}</ul>;
}Output
(filtered list, recomputed only when items or filter change)useMemo skips recalculating filtered unless items or filter change.
Key points
- useMemo caches the result of an expensive computation.
- It recomputes only when listed dependencies change.
- Overusing useMemo can add complexity without real benefit.
- Best used after profiling identifies a genuine performance issue.
๐ก Note: useMemo is an optimization, not a semantic guarantee โ don't rely on it for correctness.
