Adopting the Redux Toolkit's New createReducer Functionality
Explain the simplified reducer creation with the new `createReducer` API, showcasing its improved type inference capabilities in RTK 2.0.
import { createAction, createReducer } from '@reduxjs/toolkit';
// Define the initial state of the counter
const initialState = { value: 0 };
// Create action using createAction helper
const increment = createAction('counter/increment');
const decrement = createAction('counter/decrement');
// Create reducer using the new createReducer function
const counterReducer = createReducer(initialState, (builder) => {
// The builder callback allows us to define case reducers
// that respond to the defined actions, with improved type inference
builder
.addCase(increment, (state, action) => {
state.value += 1;
})
.addCase(decrement, (state, action) => {
state.value -= 1;
});
});
This code snippet demonstrates the use of Redux Toolkit's 'createReducer' function from RTK 2.0, simplifying reducer creation. 'createReducer' accepts the initial state and a 'builder' callback to handle actions. The builder syntax provides better type inference, ensuring that the state and action types are correct. Actions are created using the 'createAction' utility, making the code more readable and maintainable.