Sub topic 8
Extracting a useFetch hook
This chapter assumes you can write a component that fetches inside useEffect, tracks loading and error state, and cancels requests with AbortController. It also assumes you know the useState hook and basic Fetch API behavior, including checking response.ok.
Why extract a hook
A fetching component has the same parts every time: state, an effect, a fetch call, an ok check, and cleanup. If three components each load different URLs, you end up copying about twenty lines three times. Each copy is a chance to forget the abort or the status check.
A custom hook is a function whose name starts with use and that calls other hooks. It lets you move that shared logic out of components. Each component that calls the hook gets its own separate state.
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;
}Two design choices matter here.
- One state object. The earlier component used three separate
useStatecalls. Here a single object holdsstatus,data, anderror. Each update replaces all three values together, so the state can't be left in a mix likeisLoading: falsewith stale data. urlis the only dependency. The effect re-runs wheneverurlchanges. The cleanup aborts the previous request first, so a slow old response can't overwrite a newer 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 now describes only what to show. How the request runs is hidden inside the hook.
Pitfalls
The hook depends on url being a stable string. Passing a new string with the same content is fine, because React compares strings by value. The same is not true of options. If you added an options object parameter and wrote useFetch(url, { headers: {} }), the object would be new on every render. Putting it in the dependency array would then re-run the effect on every render, creating an endless fetch loop.
Also note what this hook still lacks. Two components that call useFetch with the same URL send two requests, and nothing is cached between them. Later chapters cover those limits.
Exercise
Exercise
A teammate changes useFetch to accept (url, options) and puts options in the dependency array. Callers write useFetch('/api/items', { method: 'GET' }) inline. What goes wrong, and how can you avoid it?
Show answer
The inline object is created fresh on every render, so React sees a changed dependency each time. The effect re-runs after every render, and setState inside it triggers another render, which causes a loop of requests. Avoid it by depending only on primitive values (such as url and method), by building the options inside the effect, or by having callers define a stable options object outside the component or with useMemo.
Exercise
Why does useFetch store status, data, and error in one object instead of three separate useState calls?
Show answer
A single setState call replaces all three values together, so the hook can't be left in an inconsistent combination, such as not loading but still holding data from the previous URL.