Sub topic 7
Deriving data with selectors and createSelector
This chapter assumes you can write a slice, create a store, and read state in a component with useSelector (covered in earlier chapters). It explains how to compute values from store state without causing extra renders or repeated work.
What a selector is
A selector is a function that takes the Redux state and returns a value computed from it. The simplest selectors read a field:
const selectTodos = (state) => state.todos.items
const selectFilter = (state) => state.todos.filterSelectors matter for two reasons:
- They hide the state shape. If you move
itemssomewhere else, you change one selector instead of every component. - They hold derived data logic. Store the minimum data in Redux and compute everything else, such as filtered lists, counts and totals, from it. Storing both
itemsanddoneCountinvites the two to drift apart.
How useSelector decides to re-render
useSelector runs your selector after every dispatched action. It compares the new result with the previous result using strict equality (===). If they differ, the component re-renders. If they match, it does not.
This works well for primitives and for references that only change when the data changes. Reducers built with createSlice and Immer keep an object's reference unchanged unless something inside it changed, so state.todos.items stays the same array until a todo is added, removed or edited.
The unstable-reference trap
Methods such as filter, map and slice, and object or array literals, return a new reference every time they run. A selector that uses them produces a "different" result after every action, even when the data is identical:
function DoneList() {
// Returns a new array on every call, so this component
// re-renders after every dispatched action in the app.
const done = useSelector((state) =>
state.todos.items.filter((t) => t.completed)
)
return (
<ul>
{done.map((t) => (
<li key={t.id}>{t.title}</li>
))}
</ul>
)
}The result is wasted renders, and any child that receives done as a prop (especially a memoized child) re-renders too. React-Redux 8.1 and later help you find this: in development, useSelector calls your selector twice with the same state and logs a warning if the two results are not ===.
Returning a new reference is not always a bug. It is a problem when it happens on every call for unchanged input.
Memoizing with createSelector
createSelector builds a memoized selector. It takes input selectors and a result function. It calls the input selectors, compares their results with the previous call, and runs the result function only if some input changed. Otherwise it returns the cached result, which is the same reference as before.
import { createSelector } from '@reduxjs/toolkit'
const selectTodos = (state) => state.todos.items
const selectFilter = (state) => state.todos.filter
export const selectVisibleTodos = createSelector(
[selectTodos, selectFilter],
(todos, filter) =>
filter === 'done' ? todos.filter((t) => t.completed) : todos
)createSelector is re-exported from Reselect by Redux Toolkit, so you do not install it separately. You can check the caching directly, with no React involved:
import { createSelector } from '@reduxjs/toolkit'
const selectTodos = (state) => state.todos.items
const selectFilter = (state) => state.todos.filter
const selectVisibleTodos = createSelector(
[selectTodos, selectFilter],
(todos, filter) =>
filter === 'done' ? todos.filter((t) => t.completed) : todos
)
const state = {
todos: {
filter: 'done',
items: [
{ id: 1, title: 'Write', completed: true },
{ id: 2, title: 'Test', completed: false },
],
},
}
const first = selectVisibleTodos(state)
const second = selectVisibleTodos(state)
console.log(first === second) // true
console.log(selectVisibleTodos.recomputations()) // 1The second call reuses the cached array. The recomputations() method counts how often the result function ran, which is useful in tests.
What counts as a change
Memoization compares input results by reference. Two consequences follow:
- If an input selector itself returns a new reference each time (for example
(state) => state.todos.items.map(...)), the cache never hits. Input selectors should only pick existing values out of state. - Put the expensive or reference-creating work in the result function, not in the input selectors.
Reselect 5 (used by Redux Toolkit 2.x) also checks this in development. It warns if an input selector returns a different reference when called twice with the same arguments, and if a result function just returns its input unchanged.
Selectors that take arguments
A selector often needs a value that is not in the state, such as an id or a status chosen by a component. Pass it as an extra argument, and add an input selector that reads it:
import { createSelector } from '@reduxjs/toolkit'
const selectTodos = (state) => state.todos.items
export const selectTodosByStatus = createSelector(
[selectTodos, (state, status) => status],
(todos, status) => todos.filter((t) => t.status === status)
)function StatusList({ status }) {
const todos = useSelector((state) => selectTodosByStatus(state, status))
return <span>{todos.length} items</span>
}Every input selector receives all the arguments, so the second one picks out status. In Reselect 5 the default memoizer keeps a separate cached result for each distinct argument value. With older versions (Reselect 4, bundled with Redux Toolkit 1.x), the cache held only the last result. If a component with status="open" and another with status="done" shared one selector, they overwrote each other's cache and recomputed on every call. The older workaround was to create one selector instance per component. Check your installed version before applying that workaround.
Selectors with arguments are also easy to break by passing a fresh object as the argument, such as selectX(state, { id }). A new object each render never matches the cache. Pass primitives.
Keeping selectors next to the slice
A common convention is to export selectors from the slice file, so components do not need to know the state shape:
// todosSlice.js
import { createSlice, createSelector } from '@reduxjs/toolkit'
const todosSlice = createSlice({
name: 'todos',
initialState: { items: [], filter: 'all' },
reducers: {
filterChanged(state, action) {
state.filter = action.payload
},
},
selectors: {
selectTodos: (todosState) => todosState.items,
selectFilter: (todosState) => todosState.filter,
},
})
export const { filterChanged } = todosSlice.actions
export const { selectTodos, selectFilter } = todosSlice.selectors
export default todosSlice.reducerThe selectors field of createSlice is available in Redux Toolkit 2.0 and later. Each selector receives the slice's own state, and the generated todosSlice.selectors versions take the root state, as long as the slice is mounted under its name key. In older versions, write plain functions like (state) => state.todos.items and export them.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Component re-renders after every action | Selector returns a new array or object each call | Wrap in `createSelector`, or select a primitive |
| `createSelector` recomputes every time | An input selector creates new references | Make input selectors return values already in state |
| Dev warning about a selector returning a different result | `filter`, `map` or an object literal inside `useSelector` | Move the derivation into a memoized selector |
| Selector with an id recomputes when several components use it | Reselect 4 keeps one cached result | Upgrade, or create one selector instance per component |
| Derived value is stale or out of sync | It was stored in the slice as well as computed | Remove it from state and derive it |
When not to memoize
Not every selector needs createSelector. A selector that only reads a field, such as state.todos.filter, is already stable. Memoizing a cheap computation that returns a primitive, such as items.length, adds code and no benefit. Use createSelector when the result is a new object or array, or when the computation is costly.
A related option is selecting less. useSelector((state) => state.todos.items.length) returns a number, so the component re-renders only when the count changes, and no memoization is needed.
Exercise
A component calls useSelector((state) => state.todos.items.filter((t) => t.completed)). The todos data does not change, yet the component re-renders after unrelated actions, and React-Redux logs a warning in development. Why, and how do you fix it?
Show answer
filter returns a new array on every call, so the strict equality check in useSelector fails after each action and forces a re-render. Define a memoized selector with createSelector([selectTodos], (todos) => todos.filter((t) => t.completed)). It returns the same cached array while state.todos.items keeps the same reference, so the component re-renders only when the todos change.