Blog>
Snippets

Redux Toolkit with TypeScript

Integrate TypeScript with Redux Toolkit by showcasing strong typing for state, actions, and reducers.
// store.ts
import { configureStore } from '@reduxjs/toolkit';
import { counterReducer } from './counterSlice';

export const store = configureStore({
  reducer: {
    counter: counterReducer,
  },
});

export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
This piece of code sets up the Redux store using Redux Toolkit configureStore method. It also includes the counterReducer which will be defined later. Additionally, it exports the RootState and AppDispatch types for usage with typings throughout the app.
// counterSlice.ts
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { RootState } from './store';

interface CounterState {
  value: number;
}

const initialState: CounterState = {
  value: 0,
};

export const counterSlice = createSlice({
  name: 'counter',
  initialState,
  reducers: {
    increment: (state) => {
      state.value += 1;
    },
    decrement: (state) => {
      state.value -= 1;
    },
    incrementByAmount: (state, action: PayloadAction<number>) => {
      state.value += action.payload;
    },
  },
});

export const { increment, decrement, incrementByAmount } = counterSlice.actions;

export const selectCount = (state: RootState) => state.counter.value;

export const counterReducer = counterSlice.reducer;
This code sample defines the counterSlice with 'increment', 'decrement', and 'incrementByAmount' reducers. It shows how to use createSlice with TypeScript, providing a typed state and actions. It also exports the actions and a selector to get the current count from the RootState.