Skip to main content

What is a pure reducer (a pure function)?

Definition

A pure reducer (a pure reducer function) is a function that always returns the same value for the same input and has no side effects.

More simply: A reducer is a pure function that only computes the new state from the old state and the action - and does nothing else.


Formally

A pure function:

javascript
newState = reducer(oldState, action)
  • Does not mutate oldState directly.
  • Does not make requests, log, set timers, and so on.
  • Does not reach out to external variables.
  • Always returns the same result for the same input.

Example of a pure reducer

javascript
function counterReducer(state = { count: 0 }, action) { switch (action.type) { case 'INCREMENT': return { count: state.count + 1 } case 'DECREMENT': return { count: state.count - 1 } default: return state } }

A pure function:

  • Does not mutate state
  • Does not call an API
  • Does not use Math.random()
  • Does not depend on external variables

Example of an impure reducer

javascript
function counterReducer(state = { count: 0 }, action) { switch (action.type) { case 'INCREMENT': fetch('/api/log') // side effect (an API call) return { count: state.count + 1 } case 'DECREMENT': return { count: state.count - Math.random() } // unpredictability default: return state } }

Why this is bad:

  • A reducer must be predictable.
  • Redux compares the old and new state -> if the function is unpredictable, this breaks the logic.
  • Side effects (requests, timers, logging) must run in middleware (for example, Redux Thunk, Saga, and so on), not in the reducer.

Rules for a pure reducer

RuleWhat it means
Do not mutate stateUse ...spread, map, filter, concat, but not push, splice, assign
Do not trigger side effectsNo fetch, console.log, setTimeout, alert, and so on
Do not reach out to external dataDo not use global variables, localStorage, and so on
Return new statereturn { ...state, ...changes }
Same input -> same outputPredictability

Why this matters

  1. Predictability - the reducer's result is always clear.
  2. Testability - you can just pass in state and action and check the result.
  3. Debugging - Redux DevTools can "rewind" state back and forth, because the functions have no side effects.

Summary

TermMeaning
Pure functionA function with no side effects and a deterministic result
ReducerA pure function that describes how state changes in response to an action
BenefitsPredictability, simple testing, support for time-travel debugging

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.