Back to results for “Zustand & Recoil)”
React › State Management Libraries (Redux, Zustand & Recoil)

How do middleware, such as Redux Thunk, help handle asynchronous operations like API calls in Redux?

Intermediate

Answer

Regular Redux actions are plain objects and cannot directly contain asynchronous logic like a fetch call. Middleware like Redux Thunk lets you dispatch a function instead of a plain object, and that function can perform asynchronous work, like fetching data, before eventually dispatching the real action with the actual result.
function fetchUser(id) {
  return async function (dispatch) {
    dispatch({ type: 'FETCH_USER_START' });
    const user = await fetch(`/api/users/${id}`).then((r) => r.json());
    dispatch({ type: 'FETCH_USER_SUCCESS', payload: user });
  };
}

store.dispatch(fetchUser(5));
Real-world example A team fetches user profile data through a thunk action, which dispatches a loading action first, then dispatches a success action once the actual data arrives from the server, keeping their Redux store correctly updated throughout the process.

Common follow-ups: How does Redux Toolkit's built in createAsyncThunk simplify writing this same pattern?;What is the difference between Redux Thunk and Redux Saga for handling asynchronous logic?