What is a reducer?
A reducer is a function that manages how state changes in response to specific actions (actions) and always returns a new state.
Put simply:
A reducer describes exactly how the state should change when something happens.
Formally
A reducer is a pure function with the signature:
(state, action) => newStateExample of a simple reducer
Suppose we have a counter:
function counterReducer(state, action) {
switch (action.type) {
case 'increment':
return state + 1
case 'decrement':
return state - 1
default:
return state
}
}Here:
- state is the current state (for example, the number 0)
- action is an object describing what happened ({ type: 'increment' })
- the function returns the new state (for example, 1)
In React
A reducer is used, for example, with the useReducer() hook:
const [state, dispatch] = useReducer(counterReducer, 0)- state is the current value of the counter
- dispatch is the function used to send an action:
dispatch({ type: 'increment' })In Redux
A reducer is the foundation of the Redux architecture. Redux keeps a single shared application state, and the reducer controls how it changes with each action.
In Redux, several reducers are usually combined via combineReducers().
Properties of a reducer
- A pure function: no side effects.
- Does not modify its arguments.
- Does not make API requests.
- Returns the same result for the same input.
- Immutability: does not mutate state, but creates a new object:
return { ...state, count: state.count + 1 }A memory association
A reducer is like a "state editor": it receives the current state plus an instruction ("increase", "delete", "clear") and returns a new version of the state.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.