React
The reducer pattern
Learn how the state, action and reducer trio works.
Reducer pattern
A reducer is a state machine: (state, action) => newState. It takes the current state and an action, returns a new state. It never mutates the current state; it always returns a new object.
An action is an object: { '{ type: "INCREMENT", payload: 1 }' }. type says what to do, payload carries extra data. The reducer handles each type separately with a switch(state).
Since the reducer is a pure function, it's easy to test: same input always gives same output. No side effects (no API calls, no console.log). This is a big advantage over useState for complex cases.
Switch structure
The reducer body uses switch(action.type). Each case handles one action type and returns a new state. The default branch returns the current state for unknown actions.
Each case must return a new object; mutation like state.count++ is forbidden. The correct form: return { '{ ...state, count: state.count + 1 }' }.
This structure concentrates state changes in one place. It's easy to read which action leads to which result. In large apps it's a big maintenance win.
Exercise Write counterReducer
Complete the skeleton. Write a counterReducer function. Take (state, action) parameters. With switch(action.type), in the "INCREMENT" case return { '{ ...state, count: state.count + 1 }' }. In the "DECREMENT" case return { '{ ...state, count: state.count - 1 }' }. default returns state. Export it.
Show example solution
function counterReducer(state, action) {
switch (action.type) {
case "INCREMENT":
return { ...state, count: state.count + 1 };
case "DECREMENT":
return { ...state, count: state.count - 1 };
default:
return state;
}
}
export default counterReducer;
Test yourself
-
Which two params does a reducer take?
- props and state
- state and action
- data and error
- prev and next
Show answer
state and action — Reducer takes state and action.
-
Is reducer pure?
The reducer is a ____ function; no side effects.
Show answer
The reducer is a saf function; no side effects.
-
Match the reducer parts
- state
- Current
- action
- Event
- switch
- Branch
- newState
- Output
Next lesson: Action types