Blog>
Snippets

Refactoring to Use Redux v5.0.0 Slices

Outline the refactoring process of a traditional Redux reducer into a slice using Redux Toolkit and Redux v5.0.0, with focus on typing and action creators.
import { createSlice } from '@reduxjs/toolkit';

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

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

export const counterSlice = createSlice({
  name: 'counter',
  initialState,
  reducers: {
    increment: state => {
      // Redux Toolkit allows us to write 'mutating' logic in reducers. It
      // doesn't actually mutate the state because it uses the Immer library,
      // which detects changes to a 'draft state' and produces a brand new
      // immutable state based off those changes
      state.value += 1;
    },
    decrement: state => {
      state.value -= 1;
    },
    incrementByAmount: (state, action: PayloadAction<number>) => {
      state.value += action.payload;
    },
  },
});

// Action creators are generated for each case reducer function
export const { increment, decrement, incrementByAmount } = counterSlice.actions;

export default counterSlice.reducer;
This code snippet is a refactoring of a traditional Redux reducer into a Redux Toolkit slice for a simple counter application. The createSlice function is used to define the slice name, the initial state, and three reducers: increment, decrement, and incrementByAmount. The CounterState interface ensures type safety for the state. Action creators are automatically generated for each reducer.