Redux Toolkit: createSelector & Memoization
Prevent catastrophic re-renders by memoizing derived state using Reselect 5.0 and weakMapMemoize.
What is createSelector?
createSelector is a utility from the Reselect library (bundled with Redux Toolkit) used to compute derived data.
Operations like .filter() or .map() return brand new array references every time they run. Without memoization, a standard selector computing derived state will fail React's strict equality (===) checks, forcing unnecessary component re-renders on every single state change.
The Memoization Pipeline
createSelector splits logic into two phases: Input Selectors and an Output Selector.
Input Selectors extract raw data from the state. The Output Selector performs the heavy computation (e.g., filtering). When executed, Reselect compares the return values of the Input Selectors to their previous values. If nothing changed, the Output Selector is completely skipped, and the previously cached reference is returned.
Legacy vs Modern Caching
Historically, Reselect used lruMemoize with a cache size of exactly 1. This caused a notorious 'cache thrashing' bug when rendering lists: if you used the same selector instance for multiple items, the cache was constantly overwritten, resulting in 100% cache misses.
Redux Toolkit 2.0 (Reselect 5.0) solved this by upgrading the default caching engine to weakMapMemoize.
Auto Demo: Memoization Pipeline
Tap the play button below to watch the createSelector pipeline in action. Observe how a cache hit skips the expensive Output Selector computation completely.
weakMapMemoize uses WeakMaps to safely cache the heavy Output Selector computation.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- Derived state operations like
.map()and.filter()create new references, triggering re-renders unless memoized. createSelectoruses Input Selectors to extract dependencies and skips the Output Selector if dependencies haven't changed.- RTK 2.0 uses
weakMapMemoizeas the default, providing an infinite cache size to fix list rendering bugs. - The cache is automatically cleaned up by the JS Garbage Collector via
WeakMaps.
Done with this concept?
Mark it complete to track your progress. No login needed.