Blog>
Snippets

Preventing State Mutation in Redux v5.0.1 Reducers

Exemplify a common mistake where the state is mutated in a reducer, then correct it by returning a new state object in compliance with Redux v5.0.1 best practices.
// Mistake: Mutating the state directly inside the reducer
function todoReducer(state = [], action) {
  switch (action.type) {
    case 'ADD_TODO':
      // Directly pushing into the state array is a mutation
      state.push(action.payload);
      return state;
    default:
      return state;
  }
}
This code directly mutates the state by pushing a new todo item into the state array, which is a common mistake.
// Correction: Returning a new state object instead of mutating
function todoReducer(state = [], action) {
  switch (action.type) {
    case 'ADD_TODO':
      // Return a new array with the new item, without mutating the original state
      return [...state, action.payload];
    default:
      return state;
  }
}
This code returns a new state array that includes the new todo item, thus adhering to the principle of immutability. Here we use the spread operator to create a new array.