Skip to content
← All topics

Memoization

If a function always returns the same output for the same input, cache the result so you never compute it twice. That's memoization — trading memory for speed.

Cache visualizer

Click a compute button. The first call takes a full second. Click it again — instant. The cache remembers.

|

React.memo + useCallback

Same idea, applied to components. React.memo skips re-rendering a child when its props haven't changed. useCallback keeps function references stable so memo can do its job.

|
Parent · renders: 0
List
0
Form
0
Chart
0

Without memo, every parent re-render cascades to all children — even if their props are identical.

Build it from scratch

memoize()

function memoize(fn) {
const cache = new Map()
return (...args) => {
const key = JSON.stringify(args)
if (cache.has(key)) return cache.get(key)
const result = fn(...args)
cache.set(key, result)
return result
}
}

When not to memoize

  • Cheap computations — the cache overhead costs more than recomputing.
  • Non-deterministic functions — if the output changes for the same input, caching returns stale results.
  • Functions with side effects — the side effect needs to run every time, not just once.
  • Primitives React already handles — string/number props are compared by value; memo adds nothing.

Spot this pattern

  • Repeated expensive computations with the same inputs
  • Preventing unnecessary re-renders in component trees
  • Derived data in selectors (Redux, Zustand, Recoil)

O(1) lookup, O(n) space for n unique inputs