Blog>
Snippets

Defining a Modern State Shape with createReducer

Show how to define a modern state shape using Redux Toolkit's createReducer function, emphasizing the use of TypeScript for type safety.
import { createReducer, PayloadAction } from '@reduxjs/toolkit';

// Define a type for our state
interface CounterState {
  value: number;
}

// Define the initial state using the `CounterState` type
const initialState: CounterState = {
  value: 0,
};

// Use createReducer to handle actions
const counterReducer = createReducer(initialState, {
  // Define a case reducer for the 'increment' action
  increment: (state, action: PayloadAction<number>) => {
    // Increment the state's `value` by the payload
    state.value += action.payload;
  },
  // Define a case reducer for the 'decrement' action
  decrement: (state, action: PayloadAction<number>) => {
    // Decrement the state's `value` by the payload
    state.value -= action.payload;
  }
});

export default counterReducer;
This code defines a modern state shape for a counter using TypeScript with Redux Toolkit's createReducer function. The CounterState interface defines the structure of our state. We also create an initialState object using this type. The counterReducer uses the createReducer function to respond to increment and decrement actions, updating the state's value accordingly.