Standardize thunk annotations
Create a reusable application thunk type with fixed RootState, extra-argument, and action types.
Redux Toolkit · Type Alias
ThunkAction is Redux Thunk's generic type for describing thunk functions. It captures the thunk result, state type, injected extra argument, and actions its dispatch can handle.
ThunkAction describes a function accepted by Redux Thunk middleware. It types the thunk's return value, state read by getState, optional extra argument, and the action type dispatch can accept.
ThunkAction<R, S, E, A extends Action> = (dispatch: ThunkDispatch<S, E, A>, getState: () => S, extraArgument: E) => R| Name | Type | Description |
|---|---|---|
R | R | Return type produced when the thunk function runs. |
S | S | Application state type returned by getState. |
E | E | Type of the middleware-injected extra argument. |
A | A extends Action | Action type accepted by the thunk-aware dispatcher; it extends Action. |
R, the return type of the thunk function.
import type { Action, UnknownAction } from 'redux'
import type { ThunkAction } from 'redux-thunk'
export type AppThunk<ReturnType = void> = ThunkAction<
ReturnType,
RootState,
unknown,
UnknownAction
>
type RootState = { count: number }
export const incrementLater: AppThunk<Promise<void>> = async (
dispatch,
getState
) => {
await new Promise((resolve) => setTimeout(resolve, 10))
dispatch({ type: 'counter/increment' })
console.log(getState().count)
}Defines a reusable application-specific thunk type and uses it for an asynchronous thunk.
Create a reusable application thunk type with fixed RootState, extra-argument, and action types.
Describe asynchronous or synchronous functions that dispatch actions and read current Redux state.
Model thunks that depend on services supplied through middleware.
ThunkAction is a generic function type for thunk functions. Its generic parameters describe the thunk return type, state type, extra argument type, and dispatchable action type.
Follow-up: Why is the dispatch parameter not simply the ordinary Redux Dispatch? Because thunk middleware supplies a ThunkDispatch that understands both thunk functions and regular actions.
The first generic is the thunk's return type, the second is the state returned by getState, the third is an injected extra argument, and the fourth constrains actions sent through dispatch.
Follow-up: When would the extra argument be useful? It can carry shared dependencies such as an API client supplied through thunk middleware configuration.
A reusable AppThunk alias prevents repeating the complete generic type for every thunk. The documentation example defaults its return type to void while fixing the application state, extra-argument, and action types.
Follow-up: What must components use to dispatch such thunks? They should use a middleware-aware AppDispatch, commonly exposed through a typed useDispatch hook.
ThunkDispatchAppDispatchAppThunkcreateAsyncThunkconfigureStoreuseDispatch