Migrating to Redux Toolkit with TypeScript
Show a practical code conversion example of migrating existing Redux logic to Redux Toolkit (RTK) while maintaining and improving type safety with TypeScript.
// TypeScript types and interfaces for state and actions
interface CounterState {
value: number;
}
interface IncrementAction {
type: 'increment';
payload: number;
}
interface DecrementAction {
type: 'decrement';
payload: number;
}
type KnownAction = IncrementAction | DecrementAction;
Defines TypeScript interfaces for the state and known actions.
// Previous Redux action creators
function increment(value: number): IncrementAction {
return { type: 'increment', payload: value };
}
function decrement(value: number): DecrementAction {
return { type: 'decrement', payload: value };
}
Original Redux action creator functions to increment and decrement the value.
// Previous Redux reducer
function counterReducer(state: CounterState = { value: 0 }, action: KnownAction): CounterState {
switch (action.type) {
case 'increment':
return { ...state, value: state.value + action.payload };
case 'decrement':
return { ...state, value: state.value - action.payload };
default:
return state;
}
}
The original Redux reducer that handles increment and decrement actions.
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
// Migrating to Redux Toolkit with createSlice
const counterSlice = createSlice({
name: 'counter',
initialState: { value: 0 } as CounterState,
reducers: {
increment(state, action: PayloadAction<number>) {
state.value += action.payload;
},
decrement(state, action: PayloadAction<number>) {
state.value -= action.payload;
},
},
});
export const { increment, decrement } = counterSlice.actions;
export default counterSlice.reducer;
Migrating the counter logic to Redux Toolkit using createSlice for better typing and simpler syntax. Action creators are automatically generated.