Capítulo 59 de 116

Chapter 59: useMemo

Core Idea

useMemo(calculateValue, dependencies) caches the result of an expensive calculation across renders, only re-running it when a listed dependency actually changes — the value-caching counterpart to useCallback's function-caching.

Key Concepts

  • Signature: const cached = useMemo(() => computeExpensiveValue(a, b), [a, b]) — on the first render, React runs the calculation and stores both the result and the dependency values; on later renders, if a/b are unchanged (via Object.is), React returns the cached result without re-running the function at all.
  • What justifies memoizing: a calculation that's genuinely expensive (visibly slow — profile before assuming), or a returned object/array reference that needs to stay stable so a memo-wrapped child or an Effect dependency doesn't treat it as "changed" on every render even when its contents didn't change.
  • Not free: useMemo itself has memory and comparison overhead — wrapping a genuinely cheap calculation gains nothing and adds complexity. The default should be not memoizing until profiling shows a real cost.
  • The calculation function must be pure — same purity rule as rendering (Ch 18), since React may call it, throw away the result, and call it again under certain conditions (e.g. Strict Mode's double-invoke, or discarded in-progress renders).
  • React Compiler (Ch 42) automates much of this — where it can prove safety, it inserts the equivalent memoization automatically, reducing (not eliminating) the need for manual useMemo.

Code Examples

const visibleTodos = useMemo(
  () => todos.filter(todo => todo.text.includes(filterText)),
  [todos, filterText]
);
  • What it demonstrates: an expensive filter recomputed only when todos or filterText actually change, not on every unrelated re-render of the parent.

Key Takeaways

  1. Measure before memoizing — useMemo is a targeted fix for a proven performance problem, not a default wrapper.
  2. The dependency array follows the same "must match what the function reads" rule as useEffect/useCallback.
  3. A memoized object/array reference is often needed less for raw compute cost and more to prevent downstream memo/Effect-dependency churn from a fresh reference every render.

Connects To

  • Ch 49 (useCallback): the function-caching equivalent, defined in terms of this Hook.
  • Ch 88 (memo): the child-component wrapper that benefits from stable memoized props.
  • Ch 42 (React Compiler — Introduction): automatic memoization that can reduce manual useMemo usage.