Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 41 ยท Core Concepts

Reducers in Depth

Master Redux reducers: the three rules, initial state, switch and lookup styles, splitting a big reducer into smaller ones, handling unknown actions and testing reducers as plain functions.

A reducer is the function that decides how state changes. It takes the current state and an action and returns the next state. The name comes from Array.prototype.reduce: a reducer folds a list of actions into one final state, exactly as reduce folds a list of numbers into one sum.

JavaScript
(state, action) => newState

You already wrote a few in earlier lessons. This lesson gives the rules, the common patterns and the ways to organise and test reducers, so that you can write them confidently by hand and recognise what Redux Toolkit's createSlice is doing for you.

The three rules

  1. Compute the new state only from state and action. No other inputs.
  2. Never mutate state or action. Return a new value (see State and Immutability).
  3. No side effects: no API calls, no Math.random(), no Date.now(), no reading or writing outside variables, no dispatching.

These make a reducer pure: the same inputs always produce the same output. That is why reducers are easy to test, why time travel works and why Redux can cheaply compare old and new state.

Redux Toolkit's configureStore helps you catch breaches in development: it throws when state is mutated between dispatches or inside a reducer, and it warns about non-serializable values.

Initial state and the default case

The first time the store starts it calls your reducer with state === undefined and an internal init action. Give state a default value; that is how a reducer declares its initial state. And every reducer must end with default: return state, because the store passes every action to every reducer.

JS A reducer with initial state, several cases and a default

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

No output.

Notice s === before is true for an unknown action. That matters: when a reducer returns the same reference, nothing downstream sees a change.

Switch statements and lookup tables

The switch form is the classic. A lookup table of handler functions is equivalent and easier to extend; it is also exactly what createSlice builds internally.

JavaScript
const handlers = {
  'counter/incremented': (state) => ({ ...state, value: state.value + 1 }),
  'counter/added': (state, action) => ({ ...state, value: state.value + action.payload }),
};

function counter(state = { value: 0 }, action) {
  const handler = handlers[action.type];
  return handler ? handler(state, action) : state;
}

Splitting a big reducer

A reducer for a large object becomes long fast. The remedy is reducer composition: write small reducers that each manage one piece of the state, and let a parent reducer call them. Think of it as normal function decomposition.

JS Composing reducers by hand

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

No output.

The root reducer passes each child only its own slice (state.todos, state.filter) and assembles the results. The next lessons turn this pattern into combineReducers.

Testing a reducer

Pure functions need no store, no mocks and no setup. A reducer test is: call it with a state and an action, check the result. Do that for the happy path, for the immutability (the old state is unchanged) and for the default case.

JS Testing reducers without a store

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

No output.

The same shape works in Jest, Vitest or any runner; the Testing and Tooling chapter later in the course shows the real tools.

Common reducer mistakes

  • Returning undefined. A forgotten return or missing default makes the state undefined. Redux throws a clear error for combined reducers.
  • Mutating inside a case: state.items.push(x); return state;. The reference is unchanged, so nothing updates.
  • Calling an API or Date.now() in a case. Create such values before dispatch.
  • Mixing responsibilities. A reducer for cart that also changes user data is a sign to use two reducers that both handle the same action.
  • Deep spread pyramids. If updating nested data takes five levels of ..., either flatten the state shape or use Redux Toolkit.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which of these is NOT allowed inside a reducer?

    Reducers must be pure and have no side effects. Network calls belong in thunks or middleware.
  2. 2. What must a reducer return for an action it does not recognise?

    default: return state. Returning the same reference tells everything downstream that nothing changed.
  3. 3. Where does a reducer's initial state come from?

    The store calls the reducer with undefined state at start; a default parameter value supplies the initial state.
  4. 4. How do you unit test a reducer?

    A reducer is a pure function; tests are plain input/output checks.

Summary

  • A reducer is (state, action) => newState; it must be pure, immutable and free of side effects.
  • Give the state parameter a default for the initial state and end with default: return state.
  • Use switch or a lookup table; return the same reference when nothing changes.
  • Split large reducers into small ones that each own a slice, then combine them in a root reducer.
  • Test reducers as plain functions; no store is needed.

Next: The Redux Store