Part 11 / Topic 5 of 5
Where fetching logic belongs: a useFetch custom hook
Every component that needs to fetch something was about to repeat Section 1's state modeling and Section 3's AbortController cleanup by hand - exactly the duplicated-logic problem Part 7 named. examples/05_use_fetch_custom_hook.jsx's useFetch(url) packages both once:
// examples/05_use_fetch_custom_hook.jsx
export function useFetch(url) {
const [state, setState] = useState({ phase: "loading" });
useEffect(() => {
const controller = new AbortController();
setState({ phase: "loading" });
fetch(url, { signal: controller.signal })
.then((res) => { if (!res.ok) throw new Error(`request to ${url} failed`); return res.json(); })
.then((data) => setState({ phase: "success", data }))
.catch((error) => {
if (error.name === "AbortError") return;
setState({ phase: "error", message: error.message });
});
return () => controller.abort();
}, [url]);
return state;
}
RestaurantName and RestaurantRating both call useFetch with the identical url, and neither has to know a single thing about fetch, AbortController, or the three-phase state shape. Rendering both together really fires two separate requests (examples/05_use_fetch_custom_hook.test.jsx) - exactly Part 7 Section 3's rule (a custom hook shares logic, not state; every call gets its own) applied to a real network boundary instead of a toggle. A failing url really surfaces through the identical error phase both callers already know how to render, and unmounting either one really aborts its own request without disturbing the other's.
Done here? The practice set for Part 11 — including the solutions — is on the part page.