Lesson 31 of 56 · Typescript
Redux Toolkit + TypeScript
Duration: 25 minutes
Installing
npm i @reduxjs/toolkit react-redux
npm i -D @types/react-redux
Slice with Types
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
type CounterState = { value: number };
const initialState: CounterState = { value: 0 };
const counterSlice = createSlice({
name: 'counter',
initialState,
reducers: {
increment(state) { state.value++; },
add(state, action: PayloadAction<number>) { state.value += action.payload; }
}
});
export const { increment, add } = counterSlice.actions;
export default counterSlice.reducer;
Typed useSelector
import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux';
import { RootState, AppDispatch } from './store';
export const useAppDispatch = () => useDispatch<AppDispatch>();
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;