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
useCallback
Returns a memoized version of a callback whose identity stays stable until a dependency changes. Reach for it when passing callbacks to memoized children (React.memo) or as dependencies of other hooks that would otherwise re-run on every render.
useState
Declares a piece of local state in a function component and returns the current value along with a setter. Reach for it whenever a component needs to remember a value across renders and re-render when that value changes.
useContext
Reads the current value of a React context from the nearest matching Provider above in the tree. Reach for it to share values like themes, auth, or locale without prop-drilling through every intermediate component.