Skip to content
Tutorials Center
My learning

Topics

React Reference ยท Performance and Concurrency Hooks

React useMemo hook

Reference for React useMemo: cache a calculation between renders, keep object identities stable, and know when memoization helps and when it does not.

useMemo remembers the result of a function between renders. You give it a calculation and a list of dependencies; React runs the calculation on the first render and again only when a dependency changed (compared with Object.is). Otherwise it hands back the previous result.

There are two reasons to use it: skipping an expensive calculation, and keeping the identity of an object or array stable so that a memoized child or another hook's dependency does not see a "new" value every render. It is a performance hint, not a guarantee: React may discard cached values, so your code must work without it.

JSX
const visible = useMemo(() => filterTodos(todos, filter), [todos, filter]);

Try it

Skipping a calculation on unrelated renders

Type "a": the console logs once. Click the button repeatedly: no more logs, because query did not change.

Stable identity for a memoized child

Without useMemo, { color } would be a fresh object each render and memo could never skip the child.

Syntax

JSX
const value = useMemo(calculate, dependencies);
// TypeScript: useMemo<T>(factory: () => T, deps: DependencyList): T
Name Description
calculate A pure function with no arguments that returns the value to cache. React calls it during render.
dependencies Array of every reactive value calculate reads. Compared one by one with Object.is.

Returns: the result of calculate() on the first render; on later renders either the cached result or a fresh call if a dependency changed.

Edge cases: in Strict Mode development React calls calculate twice to expose impure code. If you pass no array, the value is recalculated on every render.

Usage notes

  • Measure before you add it. Memoizing cheap work costs more than it saves. A rule of thumb: if the calculation takes about a millisecond or more, or if it feeds a memoized child, it may help.
  • The function must be pure. No fetching, no setting state, no mutations. Do those in handlers or effects.
  • Do not rely on it for correctness. React can drop the cache (for example while a component is suspended), so the result must be equal either way.
  • Dependencies must be complete. Missing one gives stale results; the eslint-plugin-react-hooks rule catches it.
  • No per-item memo in loops. You cannot call hooks in a loop; extract a component and memoize inside it, or wrap the component in memo.
  • Functions are handled by useCallback; useCallback(fn, deps) equals useMemo(() => fn, deps).
  • React Compiler can add this memoization automatically; see React Compiler.