← Lessons

quiz vs the machine

Platinum1850

Frontend

The Selector Memoization Deep

How reselect caches derived data and why input identity drives recomputation.

6 min read · advanced · beat Platinum to climb

What it is

A memoized selector computes derived data from state and caches the result. It recomputes only when its inputs change, sparing components from expensive work and needless re renders.

How reselect works

A selector built with reselect has input selectors and an output function. On each call it runs the input selectors; if all their results are reference equal to last time, it returns the cached output without rerunning the output function.

  • Inputs are compared by reference, not deep equality.
  • The output runs only when an input reference changes.
  • Combined with immutability this is both correct and fast.

The shared cache pitfall

A default selector caches only the most recent call. If two components pass different arguments, they thrash the cache. The fix is a selector factory so each component instance gets its own memoized selector.

  • One cache slot means alternating args defeat memoization.
  • Per instance selectors restore caching.
  • Never return a new object literal from an input selector.

Key idea

Memoized selectors recompute only when input references change, so rely on immutability and use selector factories to avoid cache thrash from differing arguments.

Check yourself

Answer to earn rating on the learn ladder.

1. How does reselect decide whether to recompute?

2. Why can a shared selector thrash its cache?

3. What fixes cache thrash from per component arguments?