Defining a Simple Counter Reducer with createReducer
Showcase a basic counter reducer that increments and decrements the state value using actions and the createReducer function.
import { createAction, createReducer } from '@reduxjs/toolkit';
// Action creators
const increment = createAction('increment');
const decrement = createAction('decrement');
// Reducer
const counterReducer = createReducer(0, {
[increment]: (state, action) => state + (action.payload || 1),
[decrement]: (state, action) => state - (action.payload || 1)
});
This snippet imports createReducer and createAction from Redux Toolkit. Two actions, increment and decrement, are created. The counterReducer is then defined with createReducer to update the state by incrementing or decrementing it.