Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 41 ยท Redux with React

useSelector in Depth

Master react-redux useSelector: how it compares results, why selectors that return new arrays cause extra renders, and how shallowEqual and memoized createSelector selectors fix it. Runnable demos.

useSelector is how components read Redux state, and it is also the main lever you have for performance. The rule fits in one sentence: after every dispatch, React-Redux runs your selector and compares the new result with the previous one using ===; the component renders again only if they differ. Everything in this lesson follows from that sentence.

useSelector and createSelector come from react-redux and @reduxjs/toolkit (which re-exports Reselect), so they cannot be imported in our editor. The live examples use stand-ins that follow the same comparison rule and optional equality function.

Selecting values

A selector is a plain function (state) => value. Keep selectors small and focused, and give reusable ones names, ideally next to the slice that owns the state:

JSX
// features/todos/todosSlice.js
export const selectTodos = (state) => state.todos.items;
export const selectFilter = (state) => state.todos.filter;
export const selectTodoById = (state, id) => state.todos.items.find((t) => t.id === id);

// a component
import { useSelector } from 'react-redux';
import { selectTodoById } from './todosSlice';

function TodoTitle({ id }) {
  const todo = useSelector((state) => selectTodoById(state, id));
  return <h3>{todo?.text}</h3>;
}

Selectors can take extra arguments (like id): wrap the call in an inline function. React-Redux re-runs the selector when the component renders with new props, too.

Select what you need, no more. A component that selects state.todos re-renders for any change to todos, even one it does not display. A component that selects state.todos.items.length re-renders only when the count changes.

The trap: selectors that return new objects

Two common selectors always return a new reference:

JSX
// new array every time: filter() creates a fresh array
const doneTodos = useSelector((state) => state.todos.filter((t) => t.done));

// new object every time
const view = useSelector((state) => ({ user: state.user, theme: state.theme }));

Even if the content is identical, [] !== [], so React-Redux sees "changed" after every dispatch and re-renders the component for actions that have nothing to do with it. In development, React-Redux 9 also warns when it notices a selector returning a different result for the same state ("Selector ... returned a different result when called with the same parameters").

There are three fixes: select primitives or existing references, supply an equality function, or memoise the selector.

Render counts: three ways to select a list

Press "Dispatch an unrelated action" a few times: the naive counter grows, the other two stay at 1. Press "Add a done todo": the todos did change, so all three re-render once (the naive one for the right reason this time).

shallowEqual

React-Redux exports shallowEqual, which treats two objects or arrays as equal when each key/element is ===. Pass it as the second argument:

JSX
import { useSelector, shallowEqual } from 'react-redux';

const { user, theme } = useSelector(
  (state) => ({ user: state.user, theme: state.theme }),
  shallowEqual
);

It fixes the "new object each time" case when the values inside are stable. It cannot help filter() over objects that were themselves recreated. For simple cases, though, the best fix is usually to call useSelector twice, once per value, and avoid building an object at all.

Memoised selectors with createSelector

For derived data, such as filtering, sorting or totals, use createSelector (from @reduxjs/toolkit, which re-exports Reselect). It takes input selectors and a result function and recalculates only when an input's result changes by reference.

JavaScript
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 === 'all' ? todos : todos.filter((t) => t.done === (filter === 'done')))
);

Two payoffs: the expensive calculation runs less often, and the returned array keeps the same reference when inputs are unchanged, so useSelector sees no change. Next, watch the memoisation directly:

JS createSelector only recomputes when inputs change

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

No output.

Real Reselect 5 (in Redux Toolkit 2) memoises with a WeakMap-based cache by default, so it remembers results for many different argument combinations, and it can also check input selectors for stability in development. The idea is the same as the stand-in. One caution: a selector with arguments (such as selectTodosByUser(state, userId)) is shared by every component that calls it, so give each component that needs its own cache its own selector instance, or rely on the default cache and measure your hot paths.

Selector rules of thumb

  • Do not store derived data; derive it in selectors.
  • Selectors must be pure and fast; no side effects, no dates or random numbers.
  • Return existing references when you can (state.todos, state.user); build new objects only inside createSelector.
  • Define selectors next to the slice (or in a selectors.js file), so components do not depend on the state shape.
  • Do not select the entire state (useSelector((s) => s)): the component re-renders after every action.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How does useSelector decide whether to re-render?

    A reference comparison is cheap and exact. Returning the same reference means no re-render.
  2. 2. Why does useSelector((s) => s.todos.filter(t => t.done)) re-render on unrelated actions?

    A new array each time means the result is never ===. Use createSelector or an equality function.
  3. 3. When does a createSelector result function run again?

    That memoisation is the point: unchanged inputs mean the cached result is returned.
  4. 4. Which is a good way to read two unrelated values, user and theme?

    Separate calls each return an existing reference, so each re-renders only for its own change.

Summary

  • useSelector re-renders a component only when its selector's result changes by === (or by the equality function you pass).
  • Selectors that build new arrays or objects defeat that check; avoid them or fix them.
  • Fixes: select existing references, call useSelector several times, pass shallowEqual, or memoise with createSelector.
  • Keep selectors pure, small and next to their slice; derive data instead of storing it.
  • Never select the whole state.

Next: useDispatch and Events