Blog>
Snippets

Migrating Reducers to createReducer

Provide an example of how to shift a traditional switch-case reducer into a createReducer function utilizing the builder callback pattern.
import { createAction, createReducer } from '@reduxjs/toolkit';

// Defining the initial state
const initialState = [];

// Defining actions using createAction
const todoAdded = createAction('todoAdded');
const todoToggled = createAction('todoToggled');

// The traditional switch-case reducer
/*
function todosReducer(state = initialState, action) {
 switch (action.type) {
 case todoAdded.type:
 // reducer logic to add todo
 break;
 case todoToggled.type:
 // reducer logic to toggle todo
 break;
 default:
 return state;
 }
}
*/

// Migrating to createReducer
const todosReducer = createReducer(initialState, (builder) => {
 builder
 .addCase(todoAdded, (state, action) => {
 // Reducer logic to add todo
 state.push(action.payload);
 })
 .addCase(todoToggled, (state, action) => {
 // Reducer logic to toggle todo
 const todo = state.find(todo => todo.id === action.payload);
 if (todo) {
 todo.completed = !todo.completed;
 }
 });
});
This example shows how to migrate from a traditional switch-case reducer to a createReducer function using createAction to define actions and the builder callback pattern to handle actions. createAction generates an action creator for the given action type. The createReducer function creates a reducer that is supplied with an initial state and a builder callback, where the builder object is used to add cases that associate actions with state changes. The builder callback replaces switch-case logic, allowing a more concise and expressive way to handle different action types.