Refactoring to Use createSlice for Reducer Logic
Provide an example of refactoring a traditional switch-case reducer into a cleaner createSlice function from Redux Toolkit.
// Original reducer with switch-case
const todosReducer = (state = [], action) => {
switch (action.type) {
case 'ADD_TODO':
return [...state, action.payload];
case 'TOGGLE_TODO':
return state.map(todo =>
todo.id === action.payload.id ? { ...todo, completed: !todo.completed } : todo
);
case 'REMOVE_TODO':
return state.filter(todo => todo.id !== action.payload.id);
default:
return state;
}
};
This is the traditional switch-case reducer for handling todos that we will refactor.
// Refactored reducer using createSlice from Redux Toolkit
import { createSlice } from '@reduxjs/toolkit';
const todosSlice = createSlice({
name: 'todos',
initialState: [],
reducers: {
addTodo: (state, action) => {
state.push(action.payload);
},
toggleTodo: (state, action) => {
const todo = state.find(todo => todo.id === action.payload.id);
if (todo) {
todo.completed = !todo.completed;
}
},
removeTodo: (state, action) => {
return state.filter(todo => todo.id !== action.payload.id);
}
}
});
export const { addTodo, toggleTodo, removeTodo } = todosSlice.actions;
export default todosSlice.reducer;
This is the refactored createSlice function which replaces the original todosReducer function. This new slice contains the same functionality but in a more concise and maintainable way.