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
- Generic type for the response:
useFetch<User>(url). loading,dataanderrorstates (or a singlestatus).- Abort with
AbortControllerin cleanup. - Handle
res.ok, JSON parsing errors and network errors. refetch()to retry or refresh.- Allow skipping (
url = null). - 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";23type State<T> = { data: T | null; error: Error | null; loading: boolean };45export 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 options910 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 refetching1718 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 });2728 return () => controller.abort(); // URL changed or unmounted: drop the old request29 }, [url, initKey, version]);3031 const refetch = useCallback(() => setVersion((v) => v + 1), []);32 return { ...state, refetch };33}3435// Usage36export 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.