Sub topic 8
Extracting a useFetch Hook
This chapter assumes you can write a useEffect that fetches JSON, track loading, error, and success state, and cancel a request with AbortController in cleanup. You should also know what a custom hook is: a function whose name starts with use and that calls other hooks. Here you move the fetching logic out of components and into one reusable hook, and you learn where that hook stops being enough.
Why extract the logic
Suppose two components each fetch data. Each one declares three pieces of state, creates an AbortController, checks response.ok, filters out AbortError, and returns a cleanup function. That is about 25 lines of identical code per component. A bug fix, such as forgetting to reset the error when the input changes, has to be applied in every copy.
A custom hook lets you write the logic once. Each component then states only what differs: which URL to load and how to display the result.
Two goals guide the design:
- The hook owns the request lifecycle: starting, tracking, canceling.
- The component owns presentation: what to show while loading, on error, and on success.
The hook
import { useEffect, useState } from 'react';
export function useFetch(url) {
const [state, setState] = useState({ status: 'loading', data: null, error: null });
useEffect(() => {
const controller = new AbortController();
setState({ status: 'loading', data: null, error: null });
fetch(url, { signal: controller.signal })
.then((response) => {
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
return response.json();
})
.then((data) => setState({ status: 'success', data, error: null }))
.catch((error) => {
if (error.name === 'AbortError') return;
setState({ status: 'error', data: null, error });
});
return () => controller.abort();
}, [url]);
return state;
}Walk through the choices in this code.
One state object instead of three variables. The earlier component used user, error, and isLoading as separate state. Separate variables can drift into impossible combinations, such as isLoading being true while error is also set. A single object with a status field makes each update atomic: one setState call moves the whole request from one valid state to another.
The dependency array is [url]. The effect re-runs whenever url changes. Before it re-runs, React calls the previous cleanup, which aborts the old request. This is the same race-condition protection you built by hand earlier, now written once.
Reset at the start of each run. setState({ status: 'loading', ... }) clears old data and errors. Without it, a component that changes from /api/users/1 to /api/users/2 would keep showing user 1 under a "success" status until user 2 arrives.
The AbortError early return. Aborting rejects the promise with an error named AbortError. This is an expected outcome, not a failure. If you stored it as an error, the cleanup of the old request could overwrite the state of the new one.
Using the hook
import { useFetch } from './useFetch';
function UserProfile({ userId }) {
const { status, data, error } = useFetch(`/api/users/${userId}`);
if (status === 'loading') return <p>Loading...</p>;
if (status === 'error') return <p>Error: {error.message}</p>;
return <h1>{data.name}</h1>;
}The component is now 6 lines of logic. Changing userId produces a new URL string, which changes the dependency, which restarts the request.
Why the hook must use a string, not an object
The dependency array compares values with Object.is. A string compares by value, so '/api/users/1' equals '/api/users/1' on every render. An object does not.
Consider a version of the hook that accepts options:
// Problematic: options is a new object on every render
const { data } = useFetch('/api/search', { headers: { Accept: 'application/json' } });If the hook lists options in its dependency array, the effect runs after every render, because each render creates a new object. The effect sets state, the state change causes a render, the render creates a new object, and the cycle repeats as an infinite loop of requests.
There are three ways to handle this:
- Keep the hook limited to a URL string, as above. This is the simplest option.
- Require callers to keep options stable by defining them outside the component or wrapping them in
useMemo. - Serialize the options inside the hook, for example with
JSON.stringify(options), and depend on the resulting string.
Handling a skipped request
Sometimes the URL is not ready yet. For example, a detail view might wait for a selected id. Calling fetch('/api/users/undefined') is wrong. A common extension is to accept null and skip the request:
import { useEffect, useState } from 'react';
export function useFetch(url) {
const [state, setState] = useState({ status: 'idle', data: null, error: null });
useEffect(() => {
if (url === null) {
setState({ status: 'idle', data: null, error: null });
return;
}
const controller = new AbortController();
setState({ status: 'loading', data: null, error: null });
fetch(url, { signal: controller.signal })
.then((response) => {
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
return response.json();
})
.then((data) => setState({ status: 'success', data, error: null }))
.catch((error) => {
if (error.name === 'AbortError') return;
setState({ status: 'error', data: null, error });
});
return () => controller.abort();
}, [url]);
return state;
}This adds a fourth status, idle, meaning "no request has been made." The component must handle it, usually by rendering nothing or a prompt.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Request fires in an endless loop | Object or function in the dependency array is recreated each render | Depend on primitives, or stabilize the value |
| Old data flashes after the input changes | State is not reset at the start of the effect | Set `status: 'loading'` and clear `data` first |
| `TypeError: Cannot read properties of null` | Component reads `data.name` before `status` is `'success'` | Check `status` before reading `data` |
| 404 or 500 shown as success | `response.ok` is not checked, since `fetch` only rejects on network failure | Throw when `!response.ok` |
| Error shown after navigating away | `AbortError` stored as a real error | Return early on `AbortError` |
| Two requests per mount in development | Strict Mode runs effects twice | Expected in development, and cleanup makes it safe |
What the hook does not solve
useFetch removes duplication, but each call still owns a private copy of its state. That has consequences:
- No sharing. If two components call
useFetch('/api/users/1'), the browser sends two requests. Neither knows about the other. - No cache. Navigating away and back unmounts the component and discards its state. Returning shows a loading indicator and refetches.
- No refetch control. There is no way to reload on window focus, retry after failure, or refresh after a mutation without adding more code and more options.
- Waterfalls remain. If a child component calls
useFetchonly after the parent finishes rendering its own data, the requests run in sequence.
You can add features one at a time, such as a refetch function, a cache in a module-level Map, or retry logic. Each addition brings its own edge cases: cache invalidation, deduplication of in-flight requests, and memory growth. That is the point where a purpose-built library is a better choice than a growing home-made hook, and the next chapters cover that path.
Exercise
A teammate changes useFetch to take (url, options) and lists both in the dependency array. Components call it as useFetch('/api/items', { method: 'GET' }). The network tab now shows requests firing continuously. Explain why, and give one fix.
Show answer
The { method: 'GET' } object literal is created again on every render, so Object.is sees a new value each time and the effect re-runs after every render. Each run calls setState, which triggers another render, which creates another new object, so the loop never ends. Fixes: define the options object outside the component, wrap it in useMemo, or depend on JSON.stringify(options) inside the hook, or drop the options parameter and accept only a URL string.
Exercise
In the version of useFetch that accepts null, what status does a component see on its first render when it passes null, and why is it not 'loading'?
Show answer
It sees 'idle', because the initial state is 'idle' and the effect takes the early branch for null without starting a request. Using 'loading' would tell the user that something is in progress when no request exists.