ReactMedium

Custom hook (useFetch)

A useFetch hook wraps a request in reusable state: it takes a URL (and options), returns { data, error, loading, refetch }, aborts in-flight requests when the URL changes or the component unmounts, ignores stale responses, and treats non-2xx responses as errors. It is a great interview exercise, though production apps usually use TanStack Query or SWR for caching, deduplication and retries.

Requirements

  1. Generic type for the response: useFetch<User>(url).
  2. loading, data and error states (or a single status).
  3. Abort with AbortController in cleanup.
  4. Handle res.ok, JSON parsing errors and network errors.
  5. refetch() to retry or refresh.
  6. Allow skipping (url = null).
  7. Avoid infinite loops: options objects passed inline are new each render; serialize them or depend on primitives.

Possible extensions

  • Simple in-memory cache keyed by URL.
  • Stale-while-revalidate: show cached data while refetching.
  • Response validation with Zod.
  • Retry with exponential backoff.
  • A Suspense version that throws promises (or returns a promise for use()).

Why libraries are better in production

They handle caching across components, request deduplication, background refetching, garbage collection, pagination, optimistic updates, devtools and SSR hydration. Mention this trade-off explicitly.

Code example

tsx
1import { useCallback, useEffect, useState } from "react";
2
3type State<T> = { data: T | null; error: Error | null; loading: boolean };
4
5export function useFetch<T>(url: string | null, init?: RequestInit) {
6 const [state, setState] = useState<State<T>>({ data: null, error: null, loading: !!url });
7 const [version, setVersion] = useState(0);
8 const initKey = JSON.stringify(init ?? {}); // stable dependency for inline options
9
10 useEffect(() => {
11 if (!url) {
12 setState({ data: null, error: null, loading: false });
13 return;
14 }
15 const controller = new AbortController();
16 setState((s) => ({ ...s, loading: true, error: null })); // keep old data while refetching
17
18 fetch(url, { ...JSON.parse(initKey), signal: controller.signal })
19 .then(async (res) => {
20 if (!res.ok) throw new Error(`HTTP ${res.status}`);
21 return (await res.json()) as T;
22 })
23 .then((data) => setState({ data, error: null, loading: false }))
24 .catch((error: Error) => {
25 if (error.name !== "AbortError") setState((s) => ({ ...s, error, loading: false }));
26 });
27
28 return () => controller.abort(); // URL changed or unmounted: drop the old request
29 }, [url, initKey, version]);
30
31 const refetch = useCallback(() => setVersion((v) => v + 1), []);
32 return { ...state, refetch };
33}
34
35// Usage
36export function Todo({ id }: { id: number }) {
37 const { data, error, loading, refetch } = useFetch<{ todo: string; completed: boolean }>(`https://dummyjson.com/todos/${id}`);
38 if (loading && !data) return <p>Loading…</p>;
39 if (error) return <p role="alert">{error.message} <button onClick={refetch}>Retry</button></p>;
40 return <p>{data?.completed ? "✅" : "⬜"} {data?.todo}</p>;
41}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app