React useMemo — Caching Expensive Computations and Stable References
Learn how to use useMemo to cache expensive calculations in React. Covers filtering, sorting, derived state, referential equality, and when memoization is worth the tradeoff.
Performance Hooks
Detailed Explanation
Computation Caching with useMemo
useMemo caches the result of a calculation between re-renders, recomputing only when dependencies change.
Basic Usage
const sortedItems = useMemo(() => {
return [...items].sort((a, b) => a.name.localeCompare(b.name));
}, [items]);
When useMemo Helps
- Expensive computations: Filtering/sorting thousands of items, complex math
- Stabilizing references: Preventing re-renders in children that check reference equality
- Derived state: Computing values from props or state that do not need their own useState
Filtering Large Lists
function UserList({ users, query }: { users: User[]; query: string }) {
const filtered = useMemo(() => {
return users.filter(user =>
user.name.toLowerCase().includes(query.toLowerCase())
);
}, [users, query]); // Only recomputes when users or query change
return <ul>{filtered.map(u => <li key={u.id}>{u.name}</li>)}</ul>;
}
Stabilizing Object References
const style = useMemo(() => ({
color: isDark ? "white" : "black",
fontSize: size,
}), [isDark, size]);
// style has stable reference -- won't cause child re-renders
return <StyledComponent style={style} />;
When NOT to Use useMemo
- For trivial computations (string concatenation, simple arithmetic)
- When the dependencies change on every render (negates the cache)
- As a semantic guarantee -- React may discard cached values under memory pressure
Profiling First
Before adding useMemo, use React DevTools Profiler to confirm the computation is actually a bottleneck. Unnecessary memoization adds complexity and memory overhead.
Use Case
Use useMemo for filtering and sorting large datasets, computing derived state from props, stabilizing object and array references for memoized children, and any computation that measurably impacts render performance.