TypeScript Action Creators with Redux Toolkit 2.0
Show how to define type-safe action creators using the createSlice function in Redux Toolkit 2.0, and how they integrate with TypeScript types for better development experience.
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
// Define a type for the slice state
interface CounterState {
value: number;
}
// Define the initial state using the CounterState 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) => {
// 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 automatically infer the action payload's type
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 TypeScript example creates a Redux slice for a counter feature using Redux Toolkit 2.0's createSlice. It defines type-safe action creators and state with the help of TypeScript's type system, ensuring that action payloads are correctly typed.