Sub topic 9
Typing the store and hooks with TypeScript
This chapter assumes you can read basic TypeScript (type annotations, generics, typeof), and that you have a working store from configureStore and know the useSelector and useDispatch hooks. It also assumes React-Redux 9.1 or later, which withTypes requires.
What needs types
Redux Toolkit infers most types for you. Three things need your help:
- The shape of the whole state, which components need when they read it with
useSelector. - The type of
dispatch, which includes thunk support and any other middleware you add. - The payload of each action, so that calling
amountAdded("5")is a compile error.
The approach is to derive the state and dispatch types from the store, so they never drift from the code.
Typing a slice
Give the slice state an explicit type, and type the action argument with PayloadAction<T>.
// counterSlice.ts
import { createSlice, type PayloadAction } from '@reduxjs/toolkit'
interface CounterState {
value: number
}
const initialState: CounterState = { value: 0 }
const counterSlice = createSlice({
name: 'counter',
initialState,
reducers: {
incremented(state) {
state.value += 1
},
amountAdded(state, action: PayloadAction<number>) {
state.value += action.payload
},
},
})
export const { incremented, amountAdded } = counterSlice.actions
export default counterSlice.reducerWith this in place, amountAdded(5) type checks and amountAdded('5') does not. incremented() takes no argument because its reducer declares no action parameter.
Deriving RootState and AppDispatch
Export the two types from the file that creates the store.
// 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.dispatchRootState is computed from the reducers you passed in. When you add a slice, the type updates itself. AppDispatch is taken from store.dispatch, so it knows about the thunk middleware that configureStore adds by default. A plain Dispatch type would reject thunks.
Creating pre-typed hooks
You could annotate every call, as in useSelector((state: RootState) => ...). That is repetitive and easy to forget. Create the hooks once instead.
// hooks.ts
import { useDispatch, useSelector } from 'react-redux'
import type { AppDispatch, RootState } from './store'
export const useAppDispatch = useDispatch.withTypes<AppDispatch>()
export const useAppSelector = useSelector.withTypes<RootState>()Components then import these hooks and never use the plain ones.
// Counter.tsx
import { useAppDispatch, useAppSelector } from './hooks'
import { amountAdded, incremented } from './counterSlice'
export function Counter() {
const value = useAppSelector((state) => state.counter.value)
const dispatch = useAppDispatch()
return (
<div>
<span>{value}</span>
<button onClick={() => dispatch(incremented())}>+1</button>
<button onClick={() => dispatch(amountAdded(5))}>+5</button>
</div>
)
}The state parameter is inferred as RootState, so state.counter.value autocompletes, and a misspelling such as state.countr is an error.
Common errors
| Symptom | Likely cause |
|---|---|
| `Property 'withTypes' does not exist` | React-Redux is older than 9.1. Upgrade it, or use `TypedUseSelectorHook<RootState>` instead. |
| Dispatching a thunk gives a type error | The component uses plain `useDispatch`, not `useAppDispatch`. |
| `state` is implicitly `any` inside a reducer | The slice's `initialState` has no type, or it was passed inline. |
| Circular import warnings | A slice imports `RootState` as a value. Use `import type`. |
Exercise
You add a todos slice to configureStore. Which types do you need to edit by hand so useAppSelector((state) => state.todos.items) type checks?
Show answer
None. RootState is derived with ReturnType<typeof store.getState>, so it includes todos automatically. You only need to type the slice's own state and its action payloads.