Redux Reducer Function

Reducer Function

Reducer function is the heart of Redux. It has 2 properties.

  • Pure function - reducer() is pure function. A function is said to be pure if the return value is determined by its input values only and the return value is always the same for the same input values or arguments.

  • Immutibality - reducer() should not mutate the current state. It should always return a new state.

As we know, reducers are pure functions hence they cannot do the following things:

  • It cannot change or access any global variables.

  • It cannot make any API calls.

  • It cannot call any impure function in it like date or random

Reducer Function Example

A reducer() function reduces all the actions and return a updated state with a single value.

// Define a reducer function for the counter that handles actions
const counterReducer = (state = initialState, action) => {
  // If the action is "increment", return a new state with the value incremented by 1
  if (action.type === INCREMENT) {
    return {
      ...state, // Copy the existing state
      value: state.value + action.payload, // Update the value property
    };
  }
  // If the action is "decrement", return a new state with the value decremented by 1
  else if (action.type === DECREMENT) {
    return {
      ...state, // Copy the existing state
      value: state.value - action.payload, // Update the value property
    };
  }
  // If the action is not recognized, return the existing state
  else {
    return state;
  }
};

Last updated

Was this helpful?