Sub topic 7
Deriving data with selectors and createSelector
This chapter assumes you can write a slice, configure a store, and read state with useSelector. It builds on the React-Redux bindings chapter.
What a selector is
A selector is a function that takes the Redux state and returns a value from it. Components use selectors to read data, so they don't need to know the shape of the state tree.
const selectTodos = (state) => state.todos.items
const selectFilter = (state) => state.todos.filterIf the state shape changes later, you update the selector in one place instead of every component.
Why derived data needs care
Store only the minimum data. Compute everything else when you read it. A filtered list is a good example: store items and filter, and derive the visible items.
useSelector runs after every dispatched action. It compares the new result with the previous one using strict equality (===). If they differ, the component re-renders.
A selector that calls .filter() returns a new array on every call. The reference always differs, so the component re-renders after every action, even when nothing relevant changed.
// Returns a new array each time, so the component re-renders on every action
const selectVisibleTodos = (state) =>
state.todos.filter === 'done'
? state.todos.items.filter((t) => t.completed)
: state.todos.itemsMemoizing with createSelector
createSelector comes from Reselect and is re-exported by Redux Toolkit. It takes input selectors and a result function. It caches the last result and recomputes only when an input value changes.
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
)When items and filter have the same references as the last call, createSelector returns the previous array. The component skips the re-render.
Using selectors in a component
import { useSelector } from 'react-redux'
import { selectVisibleTodos } from './todosSelectors'
function TodoList() {
const todos = useSelector(selectVisibleTodos)
return (
<ul>
{todos.map((t) => (
<li key={t.id}>{t.text}</li>
))}
</ul>
)
}Selectors that take arguments
A selector often needs a parameter, such as a user id. Take it from a second input selector.
const selectTodoById = createSelector(
[selectTodos, (state, id) => id],
(todos, id) => todos.find((t) => t.id === id)
)Call it as useSelector((state) => selectTodoById(state, id)). The cache holds only the latest arguments, so components that use different ids share one cache and evict each other. Here the result is a single item, not a new array, so the effect is mostly extra work, not extra renders.
Common errors
- Creating new references in a plain selector. Using
.filter(),.map(), or an object literal in a selector passed touseSelectorcauses renders on every action. Wrap it increateSelector. - Memoizing trivial lookups.
state.todos.itemsalready returns a stable reference. Wrapping it adds overhead and no benefit. - Input selectors that build new values. If an input selector returns a new array each time, the cache never hits.
- Calling
createSelectorinside a component body. Each render creates a new, empty cache. Define selectors at module level.
Exercise
A component uses useSelector((state) => state.todos.items.map((t) => t.text)). It re-renders after every dispatched action, including unrelated ones. Why does this happen, and how do you fix it?
Show answer
.map() returns a new array each time the selector runs, so the strict equality check in useSelector always fails. Define const selectTodoTexts = createSelector([selectTodos], (todos) => todos.map((t) => t.text)) at module level and pass it to useSelector. The result is recomputed only when state.todos.items changes.
Exercise
Why is createSelector([(state) => state.todos.items], (items) => items) pointless?
Show answer
The result function only returns its input, so there is no computation to cache. The plain input selector already returns a stable reference.