Enforcing Immutability with createReducer
Show a basic use case of createReducer from Redux Toolkit to enforce immutability in state operations, updating a numeric value in the state.
import { createAction, createReducer } from '@reduxjs/toolkit';
// Action Types
const increment = createAction('INCREMENT');
const incrementByAmount = createAction('INCREMENT_BY_AMOUNT');
// Initial State
const initialState = { value: 0 };
// Reducer
const counterReducer = createReducer(initialState, (builder) => {
// handle increment action
builder.addCase(increment, (state) => {
state.value++;
// auto-magically handles immutability thanks to Immer
});
// handle increment by amount action
builder.addCase(incrementByAmount, (state, action) => {
// Uses the action's payload to increment state
state.value += action.payload;
});
});
export default counterReducer;
This code demonstrates the use of Redux Toolkit's `createReducer` to enforce immutability when incrementing a numeric value in the state. It creates actions for incrementing by one and by a specific amount. The `createReducer` function uses the action creators to define how the state should be updated in response to those actions. Thanks to Immer, which is used internally by `createReducer`, the logic can be written in a 'mutating' way while still producing an immutable state.