Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 41 ยท Middleware and Selectors

Selectors and Memoization (Reselect)

Learn Redux selectors, why derived data should not be stored, how createSelector memoizes results, parameterized selectors and common reselect pitfalls, with runnable examples.

A selector is a function that takes the Redux state and returns a piece of it, or something computed from it. Instead of every component digging into state.shop.cart.items.filter(...), you write one function, selectVisibleItems(state), and use it everywhere. Selectors keep components independent of the state's shape and give you a natural place for derived data and performance work.

The Reselect library (re-exported by Redux Toolkit as createSelector) adds memoization: the result is cached and only recomputed when the inputs change. Reselect is not available in the editors here, so we build the memoization step by step with a stand-in you can run.

Basic selectors

JavaScript
// Plain selectors: work with real Redux or any state object
const selectTodos = (state) => state.todos.items;
const selectFilter = (state) => state.todos.filter;
const selectTodoById = (state, id) => state.todos.items.find((t) => t.id === id);

Rules of thumb:

  • Store the minimum, derive the rest. Keep items and filter in state; compute "visible items" and "count of done items" in selectors. Stored derived data goes stale and needs extra reducer code.
  • Colocate selectors with the slice that owns the state, and export them. If the state shape changes, only the slice file changes.
  • Selector names start with select.

Why memoize?

Filtering, sorting and mapping create new arrays and objects. useSelector(state => state.todos.items.filter(done)) returns a new array on every call, so useSelector thinks the value changed and re-renders the component on every store update, even unrelated ones. A memoized selector returns the same array reference when its inputs have not changed.

flowchart TD
  S["state"] --> I1["input selector: items"]
  S --> I2["input selector: filter"]
  I1 --> C{"inputs changed<br/>(===)?"}
  I2 --> C
  C -- "no" --> CACHE["return cached result"]
  C -- "yes" --> RUN["run result function"]
  RUN --> CACHE

createSelector compares the input selectors' results by reference.

A memoized selector, built from scratch

JS createSelector stand-in

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The memoized selector recomputed only twice for three calls and returned the identical array when only user changed. The plain selector produces a new array every time.

The real createSelector works the same way, with two extras: it has a default cache size of 1 (like the stand-in) and newer Reselect (v5, which Redux Toolkit 2 uses) checks in development that your input selectors are stable and that your result function is not just an identity function.

Real createSelector (read-only)

JavaScript
// Real Redux Toolkit code (read-only)
import { createSelector } from '@reduxjs/toolkit';

export const selectVisibleTodos = createSelector(
  [selectTodos, selectFilter],
  (todos, filter) => todos.filter((t) => filter === 'all' || (filter === 'done') === t.done),
);

// in a component
const visible = useSelector(selectVisibleTodos);

createSelector can be told to use a different equality check or a larger cache with createSelectorCreator or the options object (memoizeOptions, argsMemoize).

Parameterized selectors

Selectors with extra arguments, such as "todos for a user," have a problem: a cache of size one is invalidated whenever different components call it with different arguments. There are three standard answers.

1. Pass the argument through input selectors.

JavaScript
// Real Redux Toolkit code (read-only)
const selectTodosByUser = createSelector(
  [selectTodos, (state, userId) => userId],
  (todos, userId) => todos.filter((t) => t.userId === userId),
);

This is correct, but its cache holds one entry, so two components with different ids evict each other.

2. One selector instance per component. Create the selector in useMemo (or a factory like makeSelectTodosByUser()), so each component has its own cache.

3. Use a larger cache via argsMemoize: weakMapMemoize (the default in Reselect 5 for the arguments), which keeps results per distinct argument.

Here is the per-instance factory idea:

JS One selector per component

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Common pitfalls

  • Selecting too much. useSelector(state => state) re-renders on every change. Select the smallest value.
  • Returning new objects from useSelector (state => ({ a: state.a, b: state.b })). Use two useSelector calls, or a memoized selector, or shallowEqual as the second argument.
  • Memoizing trivial selectors. state => state.user.name needs no createSelector. Memoize only when the result function does real work or builds a new reference.
  • Mutating in the result function. .sort() mutates the input array. Copy first: [...todos].sort(...).
  • Input selectors that create new values (state => state.items.map(...)) break the cache. Inputs should only read, and the result function should compute.

Selectors also make state shape changes cheap, and they pair naturally with the entity adapter, which generates the common ones for you.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does useSelector(state => state.items.filter(fn)) cause extra renders?

    useSelector compares by reference, so a new array looks like a change.
  2. 2. When does a createSelector selector run its result function?

    Otherwise it returns the cached result.
  3. 3. What is a clean fix for a parameterized selector shared by many components?

    Separate instances have separate caches, so they do not evict each other.
  4. 4. Which is the safest way to sort inside a result function?

    Copying first avoids mutating the state array.

Summary

  • Selectors read and derive data from state; keep state minimal.
  • createSelector caches results and recomputes only when inputs change by reference.
  • Memoize selectors that build new arrays or objects, not trivial lookups.
  • Use per-component selector instances or weakMapMemoize for parameterized selectors.
  • Select the smallest piece of state, and never mutate in selectors.

Next: createEntityAdapter