CodeBlanks Logo Icon CodeBlanks

Reducer function

Learn to write a reducer function.

What is a reducer function?

A reducer is a pure function that takes the current state and an action and returns the new state. It usually holds a switch statement; each case matches an action type. Example: function reducer(state, action) { switch (action.type) { /* ... */ } }.

A reducer has two core principles. First it must be pure: it produces a new state only from state and action, with no side effects. Second it must not mutate the old state: it always returns a new object or value. These two principles make a reducer predictable and testable. When an unknown action arrives, returning state unchanged in the default branch is a common pattern.

A reducer example

A typical reducer manages a counter. state is a number; action.type can be "increment", "decrement" or "reset". Each matching case computes the new state.

Example: case "increment": return state + 1;. Since state is a number, the new number is returned directly. If state were an object, you would write return { ...state, count: state.count + 1 } to build a new object. A reducer must always return a new value; it must not mutate the current state. The default branch returns state unchanged for unknown actions.

Practice Write a reducer

Write a reducer function. It takes two parameters: state and action. Use switch (action.type); in the "increment" case return state + 1. In the default branch return state.

Starter code

App.js
// Write a reducer function
// Take state and action parameters
// Use switch on action.type; write increment and default branches

Sample solution

App.js
function reducer(state, action) {
  switch (action.type) {
    case "increment":
      return state + 1;
    default:
      return state;
  }
}

Questions and answers

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

1 Complete the switch case

Question
switch (action.type) {
  case "increment":
    return state + 1;
  case "____":
    return state - 1;
  default:
    return state;
}
Answer
switch (action.type) {
  case "increment":
    return state + 1;
  case "decrement":
    return state - 1;
  default:
    return state;
}

Explanation: The decrement case lowers the number by one.

2 What does a reducer return?

App.js
function reducer(state, action) {
  /* ... */
}
  • Yeni state Correct answer
  • Mutates the old state
  • Yeni action
  • Nothing

Explanation: A reducer returns new state.

3 Match each piece to its role

Term Meaning
reducer Computes state
state Current state
action Event description
switch Branch picker

All lessons in Intermediate