Every React codebase eventually grows the same tumor: the same twenty lines of fetch + useState + useEffect copy-pasted into a dozen components. Different URL, same boilerplate. One component forgets the loading flag, another forgets the cleanup, a third sets state after unmount and throws a warning in the console.
This tutorial shows you how to build a custom React hook for API calls that fixes all of that at once. We start from a realistic, messy component, and we end with a typed, reusable useFetch hook used across multiple pages, with proper loading states, error handling, request cancellation via AbortController and a refetch function.
Unlike most tutorials on this topic, we are not stopping at the happy path. We will also handle race conditions, unstable options objects, non-200 responses and we will give you a clear decision table on when a hand-rolled hook is enough and when you should reach for a data fetching library instead.
What you will build
- A
useFetch<T>hook with generics, so each page gets fully typed data. - Three reliable states: isLoading, error, data.
- Automatic cancellation of in-flight requests on unmount or when the URL changes.
- A
refetch()function for retry buttons and manual reloads. - A second hook,
useApiMutation, for POST / PUT / DELETE actions.
Prerequisites: React 18 or newer (the code works perfectly in React 19), basic TypeScript, and familiarity with useState and useEffect.

Step 1: The messy starting point
Here is the kind of component we see in almost every audit we run at Pixelfabs. It works, until it does not.
// UsersPage.tsx (before refactoring)
import { useEffect, useState } from "react";
export default function UsersPage() {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
setLoading(true);
fetch("https://api.example.com/users")
.then((res) => res.json())
.then((data) => {
setUsers(data);
setLoading(false);
})
.catch((err) => {
setError(err);
setLoading(false);
});
}, []);
if (loading) return <p>Loading...</p>;
if (error) return <p>Something went wrong</p>;
return (
<ul>
{users.map((u) => (
<li key={u.id}>{u.name}</li>
))}
</ul>
);
}
What is actually broken here
- A 404 or 500 is treated as a success.
fetchonly rejects on network failures. A 500 response still resolves, sores.json()runs on an error payload and your UI renders garbage. - No cleanup. If the user navigates away before the response lands, you call
setUserson an unmounted component. - Race conditions. If the URL depends on a prop (a search term, a page number), two requests can overlap and the slower one can overwrite the fresher result.
- Three states managed independently. Nothing stops you from having
loading === trueanderror !== nullat the same time. - Zero reuse. The next page copies all of it again.
Step 2: Extract the logic into a first custom hook
A custom hook is just a function whose name starts with use and that calls other hooks. Nothing magical. Moving the logic out of the component already gives you reuse.
// hooks/useFetch.ts (v1, naive)
import { useEffect, useState } from "react";
export function useFetch(url: string) {
const [data, setData] = useState<unknown>(null);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<Error | null>(null);
useEffect(() => {
setIsLoading(true);
fetch(url)
.then(async (response) => {
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
return response.json();
})
.then((json) => {
setData(json);
setError(null);
})
.catch((err: Error) => setError(err))
.finally(() => setIsLoading(false));
}, [url]);
return { data, isLoading, error };
}
We already fixed problem number 1 by checking response.ok. But cleanup and race conditions are still unsolved, and data is unknown. Let’s keep going.

Step 3: Add cleanup with AbortController
The cleanup function returned by useEffect runs when the component unmounts and before the effect re-runs with new dependencies. That is exactly where we cancel the request.
useEffect(() => {
const controller = new AbortController();
async function run() {
setIsLoading(true);
try {
const response = await fetch(url, { signal: controller.signal });
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
const json = await response.json();
setData(json);
setError(null);
} catch (err) {
// An aborted request is not an application error
if (controller.signal.aborted) return;
setError(err instanceof Error ? err : new Error("Unknown error"));
} finally {
if (!controller.signal.aborted) setIsLoading(false);
}
}
run();
return () => controller.abort();
}, [url]);
Why check signal.aborted instead of err.name === "AbortError"?
Both work, but checking the signal is more robust. In modern browsers an aborted fetch rejects with a DOMException named AbortError, unless you pass a custom reason to controller.abort(reason), in which case the rejection value is that reason. Checking controller.signal.aborted covers every case and also covers errors thrown later in the chain.
Important React 18/19 note: in development with Strict Mode, effects run twice on mount. Without the abort, you would see two requests and potentially two state updates. With it, the first one is cancelled cleanly. That double invocation is a feature, not a bug: it surfaces exactly the cleanup problems we are fixing here.
Step 4: Kill race conditions with a single state object
Three separate useState calls allow impossible combinations. A useReducer with a single transition per action guarantees a coherent state, and an extra cancelled flag guarantees that a stale response never writes to state.
type State<T> = {
data: T | null;
error: Error | null;
isLoading: boolean;
};
type Action<T> =
| { type: "loading" }
| { type: "success"; payload: T }
| { type: "error"; payload: Error };
function reducer<T>(state: State<T>, action: Action<T>): State<T> {
switch (action.type) {
case "loading":
return { data: state.data, error: null, isLoading: true };
case "success":
return { data: action.payload, error: null, isLoading: false };
case "error":
return { data: null, error: action.payload, isLoading: false };
default:
return state;
}
}
Note the nuance on loading: we keep the previous data in place. That gives you free “stale while revalidating” behaviour, so tables do not flash empty every time you change a filter.

Step 5: The final typed useFetch hook
Here is the complete, production-ready version. Copy it into src/hooks/useFetch.ts.
// src/hooks/useFetch.ts
import { useCallback, useEffect, useReducer, useRef, useState } from "react";
export type FetchState<T> = {
data: T | null;
error: Error | null;
isLoading: boolean;
};
type Action<T> =
| { type: "loading" }
| { type: "success"; payload: T }
| { type: "error"; payload: Error };
function reducer<T>(state: FetchState<T>, action: Action<T>): FetchState<T> {
switch (action.type) {
case "loading":
return { data: state.data, error: null, isLoading: true };
case "success":
return { data: action.payload, error: null, isLoading: false };
case "error":
return { data: null, error: action.payload, isLoading: false };
default:
return state;
}
}
/**
* Custom React hook for API calls.
* Pass null as the url to skip the request (conditional fetching).
*/
export function useFetch<T>(url: string | null, options?: RequestInit) {
const [state, dispatch] = useReducer(reducer<T>, {
data: null,
error: null,
isLoading: Boolean(url),
});
const [reloadIndex, setReloadIndex] = useState(0);
// Keep options out of the dependency array to avoid infinite loops
const optionsRef = useRef(options);
optionsRef.current = options;
useEffect(() => {
if (!url) return;
const controller = new AbortController();
let cancelled = false;
async function run() {
dispatch({ type: "loading" });
try {
const response = await fetch(url as string, {
...optionsRef.current,
signal: controller.signal,
});
if (!response.ok) {
throw new Error(
`Request failed: ${response.status} ${response.statusText}`
);
}
const json = (await response.json()) as T;
if (!cancelled) dispatch({ type: "success", payload: json });
} catch (err) {
if (controller.signal.aborted || cancelled) return;
dispatch({
type: "error",
payload: err instanceof Error ? err : new Error("Unknown error"),
});
}
}
run();
return () => {
cancelled = true;
controller.abort();
};
}, [url, reloadIndex]);
const refetch = useCallback(() => setReloadIndex((i) => i + 1), []);
return { ...state, refetch };
}
The three details most tutorials get wrong
- The options object. If you write
useFetch(url, { headers })inline, a new object is created on every render. Put it in the dependency array and you get an infinite loop. We store it in a ref instead. If your headers genuinely change (a token refresh, for example), triggerrefetch()or derive a stable key withuseMemo. - The
cancelledflag on top of the abort.controller.abort()stops the network request, but if the response body was already being parsed, the flag is your last line of defence against a stale write. - Conditional fetching. Passing
nullas the URL is the cleanest way to skip a request (waiting for an ID, for a logged-in user, for a debounced search term) without breaking the rules of hooks.
Step 6: Use the hook across multiple pages
This is where the payoff shows up. The component goes from 30 lines of plumbing to 3.
// types.ts
export type User = { id: number; name: string; email: string };
export type Product = { id: string; title: string; price: number };
// UsersPage.tsx (after refactoring)
import { useFetch } from "../hooks/useFetch";
import type { User } from "../types";
export default function UsersPage() {
const { data, isLoading, error, refetch } = useFetch<User[]>(
"https://api.example.com/users"
);
if (isLoading && !data) return <p role="status">Loading users...</p>;
if (error) {
return (
<div role="alert">
<p>{error.message}</p>
<button onClick={refetch}>Try again</button>
</div>
);
}
return (
<ul>
{data?.map((user) => (
<li key={user.id}>
{user.name} - {user.email}
</li>
))}
</ul>
);
}
// ProductDetailPage.tsx - same hook, different type, conditional fetch
import { useParams } from "react-router-dom";
import { useFetch } from "../hooks/useFetch";
import type { Product } from "../types";
export default function ProductDetailPage() {
const { id } = useParams();
const { data: product, isLoading, error } = useFetch<Product>(
id ? `https://api.example.com/products/${id}` : null
);
if (!id) return <p>Missing product id</p>;
if (isLoading) return <p>Loading product...</p>;
if (error) return <p>{error.message}</p>;
return (
<article>
<h1>{product?.title}</h1>
<p>{product?.price} EUR</p>
</article>
);
}
Notice that useFetch<User[]> and useFetch<Product> are two completely independent instances. Custom hooks share logic, never state. Each call gets its own reducer, its own controller, its own lifecycle.
Bonus: a debounced search page
Because the hook aborts the previous request whenever the URL changes, a search field is almost free:
const [term, setTerm] = useState("");
const [debounced, setDebounced] = useState("");
useEffect(() => {
const id = setTimeout(() => setDebounced(term), 300);
return () => clearTimeout(id);
}, [term]);
const { data, isLoading } = useFetch<User[]>(
debounced.length > 1
? `https://api.example.com/users?q=${encodeURIComponent(debounced)}`
: null
);

Step 7: A companion hook for POST, PUT and DELETE
useFetch is for data you read on render. Writes must be triggered by a user action, never inside an effect. That calls for a second, smaller hook.
// src/hooks/useApiMutation.ts
import { useCallback, useRef, useState } from "react";
export function useApiMutation<TBody, TResult>(
url: string,
method: "POST" | "PUT" | "PATCH" | "DELETE" = "POST"
) {
const [data, setData] = useState<TResult | null>(null);
const [error, setError] = useState<Error | null>(null);
const [isPending, setIsPending] = useState(false);
const controllerRef = useRef<AbortController | null>(null);
const mutate = useCallback(
async (body?: TBody): Promise<TResult | null> => {
controllerRef.current?.abort();
const controller = new AbortController();
controllerRef.current = controller;
setIsPending(true);
setError(null);
try {
const response = await fetch(url, {
method,
headers: { "Content-Type": "application/json" },
body: body ? JSON.stringify(body) : undefined,
signal: controller.signal,
});
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
const json = (await response.json()) as TResult;
setData(json);
return json;
} catch (err) {
if (controller.signal.aborted) return null;
setError(err instanceof Error ? err : new Error("Unknown error"));
return null;
} finally {
if (!controller.signal.aborted) setIsPending(false);
}
},
[url, method]
);
return { mutate, data, error, isPending };
}
Usage, combined with the read hook:
const { data: users, refetch } = useFetch<User[]>("/api/users");
const { mutate, isPending } = useApiMutation<NewUser, User>("/api/users");
async function handleSubmit(values: NewUser) {
const created = await mutate(values);
if (created) refetch();
}
Testing your custom hook
A reusable hook deserves a test. With Vitest and React Testing Library, renderHook plus a mocked fetch is all you need:
import { renderHook, waitFor } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { useFetch } from "./useFetch";
describe("useFetch", () => {
it("returns data on success", async () => {
vi.stubGlobal(
"fetch",
vi.fn().mockResolvedValue({
ok: true,
json: async () => [{ id: 1, name: "Ada" }],
})
);
const { result } = renderHook(() => useFetch("/api/users"));
expect(result.current.isLoading).toBe(true);
await waitFor(() => expect(result.current.isLoading).toBe(false));
expect(result.current.data).toEqual([{ id: 1, name: "Ada" }]);
expect(result.current.error).toBeNull();
});
it("surfaces an error on a non-2xx response", async () => {
vi.stubGlobal(
"fetch",
vi.fn().mockResolvedValue({ ok: false, status: 500, statusText: "Server Error" })
);
const { result } = renderHook(() => useFetch("/api/users"));
await waitFor(() => expect(result.current.error).not.toBeNull());
expect(result.current.data).toBeNull();
});
});

Custom hook or data fetching library?
Be honest about scope. A hand-rolled hook is excellent until you need caching across components, deduplication, background refresh or offline support. Here is how the options compare in 2026:
| Need | Custom useFetch | TanStack Query / SWR | React 19 use() + Suspense |
|---|---|---|---|
| Loading and error states | Yes | Yes | Via Suspense and Error Boundary |
| Request cancellation | Yes, manual AbortController | Built in | Depends on your promise source |
| Cross-component cache | No | Yes | Only if you cache the promise |
| Deduplication of identical requests | No | Yes | No |
| Retry and background refetch | Manual | Configurable | Manual |
| Bundle cost | ~0 KB | 4 KB to 13 KB gzipped | 0 KB, React built in |
| Best for | Small to mid apps, dashboards, internal tools | Data-heavy products with shared server state | RSC / framework-driven apps |
Our rule of thumb at Pixelfabs: fewer than roughly 15 endpoints and no shared cache requirement, ship the custom hook. Beyond that, the library pays for itself within a sprint. And if you are on a framework with server components, fetch on the server first and keep client hooks for truly interactive data.
Checklist before you ship your hook
- Does it check
response.okand throw a readable error? - Does it abort on unmount and on dependency change?
- Does it ignore aborted requests instead of reporting them as errors?
- Is the options object kept out of the dependency array?
- Can it skip the request entirely (null URL) without breaking the rules of hooks?
- Does it expose a
refetchso the UI can offer a retry button? - Is the return value typed with a generic rather than
any? - Does it survive Strict Mode double rendering in development?
FAQ
What is a custom React hook for an API call?
It is a plain JavaScript or TypeScript function, named with the use prefix, that encapsulates the useState / useReducer and useEffect logic needed to request data and expose data, isLoading and error to any component. The component stays focused on rendering, the hook owns the fetching.
Do custom hooks share state between components?
No. Custom hooks share logic, not state. Two components calling useFetch("/api/users") each trigger their own request and hold their own independent state. If you need shared state, lift it into a context or use a caching library.
Why does my useFetch hook loop infinitely?
Almost always because an object or array is in the dependency array of the effect. An inline { headers: {...} } creates a new reference on every render, which re-runs the effect, which sets state, which re-renders. Fix it with a ref (as we did), with useMemo, or by passing a serialised key.
Is AbortController really necessary?
Yes, for anything beyond a toy app. It prevents stale responses from overwriting fresh data when the user types fast or navigates quickly, it frees network connections, and it removes the “state update on unmounted component” class of bugs. It is supported in every modern browser and in Node 18 and above.
Can I use axios instead of fetch?
Absolutely. The structure is identical. Replace the fetch call with axios.get(url, { signal: controller.signal }), use response.data instead of response.json(), and drop the response.ok check since axios rejects on non-2xx by default.
How do I handle authentication tokens in the hook?
Do not scatter headers across pages. Wrap fetch in a small apiClient module that injects the Authorization header and the base URL, then call that client from inside the hook. Your hook signature stays clean and token refresh logic lives in exactly one file.
Should I call the hook conditionally when I have no ID yet?
Never call a hook inside an if. Call it unconditionally and pass null as the URL. The hook returns early inside the effect and no request is made.
Wrapping up
Going from copy-pasted useEffect blocks to a single useFetch<T> hook takes about an hour and removes an entire category of bugs: stale responses, missing loading flags, unhandled HTTP errors and memory leaks. Start with the final hook from Step 5, add the mutation hook when you need writes, and upgrade to a caching library only when your data layer actually demands it.
Need a hand auditing or refactoring a React codebase? The team at Pixelfabs does this every week. Get in touch and we will review your data layer with you.