Basic createReducer Usage
Show how to convert a traditional switch-case reducer to use createReducer for a simple counter application.
import { createAction, createReducer } from '@reduxjs/toolkit';
// Action Types
const increment = createAction('increment');
const decrement = createAction('decrement');
const reset = createAction('reset');
// Initial State
const initialState = { count: 0 };
// Reducer using createReducer
const counterReducer = createReducer(initialState, (builder) => {
builder
.addCase(increment, (state, action) => {
// Increments count
state.count += 1;
})
.addCase(decrement, (state, action) => {
// Decrements count
state.count -= 1;
})
.addCase(reset, (state, action) => {
// Resets count to zero
state.count = 0;
});
});
export default counterReducer;
This code creates a counter reducer with increment, decrement, and reset actions using Redux Toolkit's createReducer. The createAction function is used to define action types, and createReducer is used in place of a traditional switch-case reducer.