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
oldStatedirectly. - 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
| Rule | What it means |
|---|---|
| Do not mutate state | Use ...spread, map, filter, concat, but not push, splice, assign |
| Do not trigger side effects | No fetch, console.log, setTimeout, alert, and so on |
| Do not reach out to external data | Do not use global variables, localStorage, and so on |
| Return new state | return { ...state, ...changes } |
| Same input -> same output | Predictability |
Why this matters
- Predictability - the reducer's result is always clear.
- Testability - you can just pass in
stateandactionand check the result. - Debugging - Redux DevTools can "rewind" state back and forth, because the functions have no side effects.
Summary
| Term | Meaning |
|---|---|
| Pure function | A function with no side effects and a deterministic result |
| Reducer | A pure function that describes how state changes in response to an action |
| Benefits | Predictability, simple testing, support for time-travel debugging |
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.