Blog>
Snippets

Type-Safe Actions with Redux Toolkit and TypeScript

Showcase the creation of a Redux action using the createSlice function from RTK 2.0, demonstrating type inference with TypeScript for payload and state.
import { createSlice, PayloadAction } 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,
  // The `reducers` field lets us define reducers and generate associated actions
  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;
    },
    // Use the PayloadAction type to declare the contents of `action.payload`
    incrementByAmount: (state, action: PayloadAction<number>) => {
      state.value += action.payload;
    }
  }
});

// Action creators are generated for each case reducer functio
This code snippet creates a counter slice with a slice state type of CounterState, an initial state, and three reducers using the Redux Toolkit createSlice function. It includes type-safe actions using TypeScript's PayloadAction type.
const { increment, decrement, incrementByAmount } = counterSlice.actions;

export default counterSlice.reducer;
This code snippet exports the generated action creators and the reducer from the counter slice, allowing them to be used in the rest of the application.