CodeBlanks Logo Icon CodeBlanks

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.

Practice 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.

Starter code

App.jsx
// Write the counterReducer function here

Sample solution

App.jsx
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;

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which two params does a reducer take?

  • props and state
  • state and action Correct answer
  • data and error
  • prev and next

Explanation: Reducer takes state and action.

2 Is reducer pure?

Question
The reducer is a ____ function; no side effects.
Answer
The reducer is a saf function; no side effects.

Explanation: Reducer is a pure function.

3 Match the reducer parts

Term Meaning
state Current
action Event
switch Branch
newState Output

All lessons in Intermediate