Blog>
Snippets

Ensuring State Immutability with Redux Toolkit

Present how Redux Toolkit's createReducer function utilizes Immer under the hood to protect state immutability by writing a reducer handling an action that updates a nested state object.
import { createAction, createReducer } from '@reduxjs/toolkit';

// Define an action
const updateNestedField = createAction('updateNestedField');

// Initial state with nested object
const initialState = {
  profile: {
    name: 'Alice',
    details: {
      age: 25,
      location: 'Wonderland'
    }
  }
};

// Reducer that handles the action
const myReducer = createReducer(initialState, (builder) => {
  builder.addCase(updateNestedField, (state, action) => {
    // Directly mutate the state, Immer makes it safe
    state.profile.details.age = action.payload.age;
    state.profile.details.location = action.payload.location;
  });
});
This code utilizes Redux Toolkit's createReducer function along with Immer. It sets up a reducer for a nested state object. When the action 'updateNestedField' is dispatched, we update the nested details object inside the profile key with the new age and location provided by the action's payload. Immer, which is used internally by createReducer, allows us to write code that directly mutates the state without breaking Redux's immutability principle.