ReactMedium
What is Redux Thunk?
Redux Thunk is middleware that lets you dispatch functions instead of plain action objects. The function receives dispatch and getState, so it can run async logic such as API calls and dispatch real actions when done. Redux Toolkit includes it by default and wraps the common pattern in createAsyncThunk.
What a thunk is
A function returned by an action creator: const fetchUser = (id) => async (dispatch, getState) => { ... }. When dispatched, the thunk middleware calls it instead of passing it to reducers.
createAsyncThunk
createAsyncThunk("users/fetch", async (id, thunkAPI) => { ... }).- Automatically dispatches
users/fetch/pending,/fulfilled(with the returned value) and/rejected(with the error). thunkAPIprovidesdispatch,getState,signal(anAbortSignalfor cancellation),rejectWithValueandextra(injected dependencies like an API client).- The dispatched promise has
.unwrap()to get the payload or throw. - A
conditionoption can skip the request if data is already loading or cached.
When to use thunks
- Async calls that update Redux state.
- Logic that needs
getStatebefore deciding what to dispatch. - Coordinating multiple dispatches.
When to use something else
- RTK Query: for most data fetching and caching, so you do not write fetch thunks and loading flags by hand.
- Listener middleware: for reacting to actions ("when X happens, do Y").
- Sagas: for complex long-running workflows (rarely needed now).
Code example
tsx
1import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";23type User = { id: string; name: string };45export const fetchUser = createAsyncThunk<User, string, { rejectValue: string }>(6 "users/fetch",7 async (id, { signal, rejectWithValue }) => {8 const res = await fetch(`/api/users/${id}`, { signal }); // aborted if the thunk is cancelled9 if (res.status === 404) return rejectWithValue("User not found");10 if (!res.ok) throw new Error(`HTTP ${res.status}`);11 return (await res.json()) as User;12 }13);1415const usersSlice = createSlice({16 name: "users",17 initialState: { current: null as User | null, status: "idle" as "idle" | "loading" | "failed", error: "" },18 reducers: {},19 extraReducers: (b) =>20 b.addCase(fetchUser.pending, (s) => void (s.status = "loading"))21 .addCase(fetchUser.fulfilled, (s, a) => { s.status = "idle"; s.current = a.payload; })22 .addCase(fetchUser.rejected, (s, a) => { s.status = "failed"; s.error = a.payload ?? a.error.message ?? ""; }),23});2425export default usersSlice.reducer;2627// Hand-written thunk (what createAsyncThunk automates):28// const fetchUserManual = (id: string) => async (dispatch, getState) => { dispatch(pending()); ... };
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.