What is memoization, and where is it useful in JavaScript?

JavaScript Performance Intermediate 2–3 Yrs3–5 Yrs Conceptual 1 min read

Quick Answer

Memoization caches a function's result keyed by its arguments, so a repeated call with the same inputs returns the cached value instead of recomputing. It only works for pure functions (same input → same output). Common uses: expensive calculations, recursive algorithms (fibonacci), and React's useMemo/useCallback.

Memoization is caching the output of a function based on its inputs, so calling it again with the same arguments just returns the stored result. It only makes sense for pure functions, and it only helps if the function is expensive and actually gets called repeatedly with the same inputs — otherwise the cache lookup and storage cost more than they save. The classic example is a recursive fibonacci going from exponential to linear. In React it's useMemo for a computed value and useCallback for a stable function reference.

  • Simple memoize: a closure with a Map keyed by a serialised argument (usually JSON.stringify(args) or the single primitive arg).
  • Watch cache growth — add an eviction policy or size cap for long-lived caches.
  • Not useful if the function is cheap or rarely called with repeat args — the bookkeeping costs more.
  • React: useMemo caches a value, useCallback caches a function reference, both keyed by a dependency array.