Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 41 ยท Async Logic and Data Fetching

Async Logic and Thunks

Learn why reducers must stay pure, how thunk middleware lets you dispatch functions, and how to model loading, success and error states for async work in Redux.

A Redux reducer is a pure function: given the same state and action it must return the same result, with no network calls, timers or random numbers. That rule makes Redux predictable and easy to test, but real apps spend much of their time waiting for servers. So where does the asynchronous code go?

The answer is: outside the reducer, before or after you dispatch. The store only ever receives plain action objects. A thunk is the simplest way to put async code next to the store: instead of dispatching an object, you dispatch a function, and a small piece of middleware runs that function with dispatch and getState.

Redux packages (redux, @reduxjs/toolkit, redux-thunk) are not available in the live editors on this site. The examples below use a tiny hand-written store and a hand-written thunk middleware, so you can run and change them. Real Redux code is shown in read-only blocks and is labelled as such.

Why async code cannot live in a reducer

Suppose a reducer fetched data. Two identical dispatches could produce different states, the time-travel debugger could not replay actions, and tests would need a fake network. Instead, Redux splits an async operation into several plain actions that describe what happened:

  1. users/pending: the request started.
  2. users/fulfilled: the request succeeded, and the payload holds the data.
  3. users/rejected: the request failed, and the payload holds an error message.

The reducer handles each of them synchronously. The async part, calling the server, is done by code that dispatches these three actions at the right moments.

sequenceDiagram
  participant UI as Component
  participant T as Thunk
  participant S as Store
  participant API as Server
  UI->>T: dispatch(fetchUsers())
  T->>S: dispatch(pending)
  T->>API: request
  API-->>T: response
  T->>S: dispatch(fulfilled, data)
  S-->>UI: new state, re-render

The thunk is the only place that knows about the network. The store sees three ordinary actions.

A thunk is just a function

In real Redux, redux-thunk is included in Redux Toolkit's default store. Its entire logic is one line: if the dispatched value is a function, call it with dispatch and getState; otherwise pass it on. Here it is, together with a minimal store, so you can watch it work.

JS Thunk middleware stand-in

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The first dispatch is an ordinary action. The second is a function: the middleware calls it, the function schedules the timer, and later dispatches a normal action itself. Notice that the thunk can read the current state with getState(), which is useful when the work depends on what is already loaded.

Modelling loading, success and error

Almost every request needs the same three pieces of state: the data, a status, and an error. A common shape is:

JavaScript
{ items: [], status: 'idle' /* 'loading' | 'succeeded' | 'failed' */, error: null }

Using one status string instead of several booleans (isLoading, hasError, ...) avoids impossible combinations such as "loading and failed at once".

JS A fetch thunk with status

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The console shows loading, succeeded, loading, failed. Because the thunk is an async function, await store.dispatch(...) waits until it has finished, which is handy in tests and when a component must do something after the request.

The real thing: Redux Toolkit

In a Redux Toolkit app you do not write redux-thunk yourself: configureStore already includes it. A hand-written thunk looks like this (read-only; the packages are not available in the editor):

JavaScript
// Real Redux Toolkit code (read-only)
export const fetchUser = (id) => async (dispatch, getState, extra) => {
  dispatch(userRequested());
  try {
    const res = await fetch(`/api/users/${id}`);
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    dispatch(userReceived(await res.json()));
  } catch (err) {
    dispatch(userFailed(err.message));
  }
};

// in a component
dispatch(fetchUser(7));

Writing the three actions by hand gets repetitive. createAsyncThunk generates them for you, and RTK Query removes most of this code for data fetching entirely.

Where thunks fit best

  • Good: a request with a status, logic that needs getState() (for example "only fetch if not already loaded"), several dispatches in sequence, small bits of orchestration.
  • Less good: caching, deduplicating requests and refetching: use RTK Query. Long-running, reactive workflows: see the listener middleware.

Common mistakes are putting fetch inside a reducer (never), forgetting try/catch so a failed request leaves the status stuck at loading, and dispatching the thunk function without calling it (dispatch(fetchUser) instead of dispatch(fetchUser(7))).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why must a reducer not perform a network request?

    Purity makes Redux predictable, testable and replayable. Async work belongs in thunks or other middleware.
  2. 2. What does thunk middleware do when it receives a function?

    That is its whole job: functions are called with (dispatch, getState); everything else goes to next(action).
  3. 3. Why is a single status string better than several booleans?

    One value can only be in one state at a time.
  4. 4. A request fails and the thunk has no try/catch. What is likely to happen?

    Nothing dispatches the rejected action, so the UI shows a spinner forever.

Summary

  • Reducers stay pure; async code runs in thunks (or other middleware) that dispatch plain actions.
  • A thunk is a function (dispatch, getState) => ...; thunk middleware calls it.
  • Split a request into pending, fulfilled and rejected actions and keep a status string.
  • await store.dispatch(thunk()) waits for the thunk to finish.
  • Redux Toolkit includes thunk and gives you createAsyncThunk to remove the boilerplate.

Next: createAsyncThunk