Sub topic 9
Modeling async work: loading, success, error
This chapter shows how to use a reducer to track a request that is in progress, has succeeded, or has failed. It assumes you can already write a reducer and dispatch actions, and that you know useEffect and its cleanup function. It also assumes you know what fetch returns.
Why separate useState calls drift apart
A common first version of a data-loading component uses three pieces of state:
const [loading, setLoading] = useState(false);
const [data, setData] = useState(null);
const [error, setError] = useState(null);These three values are meant to describe one thing: where the request is in its life. But they can be set independently, so they can also describe situations that make no sense:
loadingistrueanderroris set, so the component is loading and failed at once.dataholds the result of the previous URL whileloadingistruefor the new one. The screen may show old data under a new heading.- A retry forgets to call
setError(null), so a stale error stays on screen next to fresh data.
Every handler must remember to update all three values in the right order. Each missed call produces an impossible combination. A reducer fixes this by making one action change all related fields in one step.
One status field instead of several flags
Replace the independent booleans with a single status string that can hold exactly one of four values:
| Status | Meaning | `data` | `error` |
|---|---|---|---|
| `idle` | Nothing requested yet | `null` | `null` |
| `loading` | Request in flight | `null` | `null` |
| `success` | Request finished with a result | the result | `null` |
| `error` | Request failed | `null` | a message |
Because status holds exactly one value, "loading and failed at once" cannot be represented. The data and error columns show which fields are meaningful in each status.
The transitions between statuses are also limited. A request starts from idle (or restarts from success or error), and moves to success or error when it settles.
Three actions that record what happened
Name the actions after events, not after the state they produce. fetch_started, fetch_succeeded and fetch_failed describe what happened. The reducer decides what each event means for the state.
The reducer never calls fetch. A reducer must stay pure: given the same state and action, it returns the same result and does nothing else. It only turns an event into the next state.
import { useEffect, useReducer } from 'react';
const initialState = { status: 'idle', data: null, error: null };
function fetchReducer(state, action) {
switch (action.type) {
case 'fetch_started':
return { status: 'loading', data: null, error: null };
case 'fetch_succeeded':
return { status: 'success', data: action.data, error: null };
case 'fetch_failed':
return { status: 'error', data: null, error: action.error };
default:
throw Error('Unknown action: ' + action.type);
}
}
export default function User({ url }) {
const [state, dispatch] = useReducer(fetchReducer, initialState);
useEffect(() => {
let ignore = false;
dispatch({ type: 'fetch_started' });
fetch(url)
.then(res => {
if (!res.ok) throw new Error('HTTP ' + res.status);
return res.json();
})
.then(data => {
if (!ignore) dispatch({ type: 'fetch_succeeded', data });
})
.catch(error => {
if (!ignore) dispatch({ type: 'fetch_failed', error: error.message });
});
return () => {
ignore = true;
};
}, [url]);
if (state.status === 'loading') return <p>Loading...</p>;
if (state.status === 'error') return <p>Error: {state.error}</p>;
if (state.status === 'success') return <pre>{JSON.stringify(state.data, null, 2)}</pre>;
return null;
}Each reducer case returns a complete object. fetch_started explicitly resets data and error, so a retry cannot show a leftover error. Nothing outside the reducer writes to these fields.
Where the side effect lives
The network call sits in useEffect, because it is a side effect and effects are where React expects them. The effect runs after render, and every dispatch inside it feeds an event back to the reducer. The data flows in a loop:
- The component renders with the current state.
- The effect starts a request and dispatches
fetch_started. - React re-renders with
status: 'loading'. - The promise settles, and the effect dispatches
fetch_succeededorfetch_failed. - React re-renders with the final state.
The [url] dependency array restarts this loop whenever the URL changes. The effect dispatches fetch_started first, so the old result is cleared at that moment.
Handling stale responses with the ignore flag
Suppose url changes from /users/1 to /users/2 while the first request is still in flight. The responses can arrive out of order. If /users/1 finishes last, its data would overwrite the data for user 2, and the screen would show the wrong user.
The ignore variable prevents this. Each effect run creates its own ignore. When url changes, React runs the cleanup function of the previous effect, which sets that run's ignore to true. When the old promise settles, it sees ignore === true and dispatches nothing. Only the latest run can update state.
The same mechanism covers Strict Mode. In development, React mounts a component, unmounts it, and mounts it again to expose missing cleanup. Your effect therefore runs twice. The first run is cleaned up and ignored, and the second run's result is used. You will see two network requests in development, but only one result reaches the reducer.
Checking res.ok
fetch only rejects its promise on network failures such as a dropped connection. A 404 or 500 response resolves normally. If you skip the res.ok check, res.json() may parse an error body, or throw a confusing parse error, and the reducer records a success or an unhelpful message. Throwing new Error('HTTP ' + res.status) sends HTTP failures into the same .catch path as network failures, so one action handles both.
Retrying and refreshing
To let the user retry, add a counter that the effect depends on. It does not belong in the reducer, because it only exists to restart the effect:
import { useEffect, useReducer, useState } from 'react';
const initialState = { status: 'idle', data: null, error: null };
function fetchReducer(state, action) {
switch (action.type) {
case 'fetch_started':
return { status: 'loading', data: null, error: null };
case 'fetch_succeeded':
return { status: 'success', data: action.data, error: null };
case 'fetch_failed':
return { status: 'error', data: null, error: action.error };
default:
throw Error('Unknown action: ' + action.type);
}
}
export default function Profile({ url }) {
const [state, dispatch] = useReducer(fetchReducer, initialState);
const [attempt, setAttempt] = useState(0);
useEffect(() => {
const controller = new AbortController();
dispatch({ type: 'fetch_started' });
fetch(url, { signal: controller.signal })
.then(res => {
if (!res.ok) throw new Error('HTTP ' + res.status);
return res.json();
})
.then(data => dispatch({ type: 'fetch_succeeded', data }))
.catch(error => {
if (error.name === 'AbortError') return;
dispatch({ type: 'fetch_failed', error: error.message });
});
return () => controller.abort();
}, [url, attempt]);
return (
<>
{state.status === 'loading' && <p>Loading...</p>}
{state.status === 'error' && (
<p>
Error: {state.error}{' '}
<button onClick={() => setAttempt(a => a + 1)}>Retry</button>
</p>
)}
{state.status === 'success' && (
<pre>{JSON.stringify(state.data, null, 2)}</pre>
)}
</>
);
}This version replaces the ignore flag with AbortController. The cleanup calls controller.abort(), which cancels the in-flight request and makes its promise reject with an AbortError. The catch block returns early for that error. Without that check, every cleanup would dispatch a fetch_failed action for a request you cancelled on purpose.
Clicking Retry changes attempt. That re-runs the effect, which dispatches fetch_started, which clears the error.
Design choices and edge cases
Clearing data on start. The reducer above sets data: null on fetch_started. This avoids showing the previous user's data during a reload. If you prefer to keep the old data visible while refreshing, return { ...state, status: 'loading', error: null } instead. Then the UI can show old data with a loading indicator. This is a product choice. Make it deliberately, and write it in the reducer, not in the component.
The error value. Store a string or a small object, not the raw Error instance, if you plan to log or serialize state. Error objects do not serialize well with JSON.stringify.
Unknown actions. Throwing in the default case turns typos such as 'fetch_succeded' into an immediate, visible error during development. Returning state silently would hide the bug.
Several requests in one component. Give each request its own useReducer call, or add a key to the state. Do not share one reducer between unrelated requests, because their statuses would overwrite each other.
Use a library when needs grow. Caching, deduplication, background refetching and pagination are outside what this pattern handles. Libraries built for server state, such as TanStack Query, solve them. The reducer pattern here is still worth knowing, because those libraries use the same status model internally, and it suits one-off requests and custom async workflows.
Summary of the pattern
- Model the request as one
statusplus the fields meaningful for that status. - Dispatch events (
fetch_started,fetch_succeeded,fetch_failed), not setters. - Keep
fetchinuseEffect. The reducer stays pure. - Guard against stale results with an
ignoreflag or anAbortController. - Treat non-OK HTTP responses as failures by checking
res.ok.
Exercise
In the reducer from this chapter, the user is viewing user 1 (status success) and then the url prop changes to user 2. The request for user 2 fails with HTTP 500. Write the sequence of actions the reducer receives and the state after each one. Then explain what would be shown on screen if fetch_started returned { ...state, status: 'loading' } instead of resetting data and error.
Show answer
The reducer receives fetch_started, then fetch_failed with error: 'HTTP 500'. After fetch_started the state is { status: 'loading', data: null, error: null }, so the screen shows "Loading...". After fetch_failed the state is { status: 'error', data: null, error: 'HTTP 500' }, so the screen shows "Error: HTTP 500". With the shorter fetch_started, the state during loading would be { status: 'loading', data: <user 1>, error: null }. The component above checks status first, so it would still show "Loading...". After fetch_failed, data would still hold user 1's result, and any code that reads state.data without checking status would display the wrong user next to an error. Resetting the fields prevents this.