Blog>
Snippets

Avoiding Mutations in createReducer

Provide an example that emphasizes the use of immutable update patterns within createReducer to ensure state is updated correctly without mutations.
import { createReducer } from '@reduxjs/toolkit';

// Define the initial state for the reducer
const initialState = { list: [] };

// Use createReducer to handle actions immutably
const listReducer = createReducer(initialState, {
    // Add a new item to the list
    itemAdded: (state, action) => {
        // Instead of mutating the state, we use push provided by Immer
        state.list.push(action.payload);
    },
    // Remove an item from the list by index
    itemRemoved: (state, action) => {
        // Create a new list without the item at the index
        state.list.splice(action.payload, 1);
    },
    // Update an item in the list
    itemUpdated: (state, action) => {
        // Directly assign the new value to the index, which is a safe mutation with Immer
        state.list[action.payload.index] = action.payload.item;
    }
});

export default listReducer;
This code snippet shows a Redux reducer defined using the createReducer function from Redux Toolkit. It demonstrates handling actions with immutable update patterns provided by Immer. Actions like adding, removing, and updating items in a list are handled without directly mutating the state. Instead, operations that would typically mutate the state, such as push and splice, can be used safely within the reducer functions as Immer handles the immutability under the hood.