performance

useMemo

Memoizes the result of a computation between renders, recomputing only when a dependency changes. Reach for it when a calculation is genuinely expensive or when you need a stable reference (e.g. as a dep of another hook or a context value).

const cached = useMemo(() => compute(a, b), [a, b])

Parameters & Behavior

Parameter Purpose
calculateValue Pure function whose return value gets cached
dependencies Recompute when any dep changes (Object.is compared)
stable reference Same object/array identity across renders while deps are stable
cache is per-instance Each component instance has its own memo cache; may be discarded under memory pressure

Examples

const sorted = useMemo(() => [...items].sort(cmp), [items]);

Avoid re-sorting a large list on every render

const value = useMemo(() => ({ user, logout }), [user]);
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;

Stable context value keeps consumers from re-rendering unnecessarily

const filtered = useMemo(() => rows.filter(r => r.status === status), [rows, status]);

Recompute the filtered view only when inputs change

const chartData = useMemo(() => aggregate(events), [events]);

Cache an expensive aggregation feeding a chart

Gotcha

Not a semantic guarantee — React may throw away the cache and recompute, so the function must be pure. Wrapping cheap work costs more than it saves; measure first.

Related hooks

← All React hooks · Fix hydration mismatch