Blog>
Snippets

Defining and Using Type-Safe Action Creators

Show a code sample for defining type-safe action creators with Redux Toolkit and invoking them within a component.
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,
  reducers: {
    // Use the PayloadAction type to declare the contents of `action.payload`
    increment: state => {
      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;
This code defines a Redux slice for a counter using createSlice from Redux Toolkit. It includes type-safe actions for increment, decrement, and increment by a specific amount.
import React from 'react';
import { useDispatch } from 'react-redux';
import { increment } from './counterSlice'; // Import the action creator

export const CounterComponent = () => {
  // Use `useDispatch` to get the dispatch function
  const dispatch = useDispatch();

  return (
    <div>
      <button onClick={() => dispatch(increment())}>Increment counter</button>
    </div>
  );
};
This React component uses the useDispatch hook to dispatch the type-safe increment action defined in the counterSlice.