Migrating Switch-Case Reducers to createSlice
Demonstrate the process of refactoring a traditional switch-case reducer into a more declarative reducer using `createSlice`.
// Traditional switch-case reducer
function counterReducer(state = { count: 0 }, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default:
return state;
}
}
This is the traditional way of writing a reducer with switch-cases to handle different actions.
// Import createSlice from Redux Toolkit
import { createSlice } from '@reduxjs/toolkit';
// Refactoring the traditional reducer to use createSlice
const counterSlice = createSlice({
name: 'counter',
initialState: { count: 0 },
reducers: {
increment: state => {
state.count += 1;
},
decrement: state => {
state.count -= 1;
}
}
});
// Export the generated action creators and the reducer
export const { increment, decrement } = counterSlice.actions;
export default counterSlice.reducer;
The traditional reducer is refactored using createSlice from Redux Toolkit. It automatically generates action creators and handles the switch-case logic declaratively.