useFetch
Declarative fetch with abort & races handled.
Import
TypeScript
import { useFetch } from '@/hooks';API
Signature
useFetch<T>(url, options?) → { data, loading, error, refetch, abort }
When to use
Client-side REST reads with loading/error/refetch.
SSR / Next.js
Client-side. Prefer RSC for first-paint server data.
Live playground
Edit the example and see it run against the real @/hooks package in this app.
Live playgroundEdit · run with real
@/hooks · useFetchEditor
type User = { id: number; name: string }; function Users() { const { data, loading, error, refetch } = useFetch<{ users: User[] }>('/api/users'); if (loading) return <p>Loading…</p>; if (error) return <p>{error.message}</p>; return ( <div> <ul>{data?.users.map((u) => <li key={u.id}>{u.name}</li>)}</ul> <button onClick={() => void refetch()}>Refresh</button> </div> ); }
Preview
Implementation source
Full library source for useFetch — copy into your project when you are not installing a package yet.
hooks/async/useFetch.ts
import { useCallback, useEffect, useRef, useState } from 'react';
import { useIsMounted } from '../utility/useIsMounted';
export interface UseFetchOptions<T> extends Omit<RequestInit, 'signal'> {
/** @default true */
immediate?: boolean;
/** Parse response body. @default res => res.json() */
parser?: (response: Response) => Promise<T>;
/** Skip fetch when false. */
enabled?: boolean;
onSuccess?: (data: T) => void;
onError?: (error: Error) => void;
}
export interface UseFetchReturn<T> {
data: T | undefined;
error: Error | null;
loading: boolean;
status: 'idle' | 'loading' | 'success' | 'error';
response: Response | null;
refetch: (init?: RequestInit) => Promise<T | undefined>;
abort: () => void;
}
/**
* Declarative fetch with abort, race protection, and unmount safety.
* Do not hardcode base URLs — pass full or app-relative URLs.
*/
export function useFetch<T = unknown>(
url: string | null | undefined,
options: UseFetchOptions<T> = {},
): UseFetchReturn<T> {
const {
immediate = true,
parser = (res: Response) => res.json() as Promise<T>,
enabled = true,
onSuccess,
onError,
...requestInit
} = options;
const isMounted = useIsMounted();
const abortRef = useRef<AbortController | null>(null);
const requestId = useRef(0);
const [data, setData] = useState<T | undefined>(undefined);
const [error, setError] = useState<Error | null>(null);
const [loading, setLoading] = useState(false);
const [status, setStatus] = useState<'idle' | 'loading' | 'success' | 'error'>('idle');
const [response, setResponse] = useState<Response | null>(null);
const abort = useCallback(() => {
abortRef.current?.abort();
}, []);
const refetch = useCallback(
async (init?: RequestInit) => {
if (!url || !enabled) return undefined;
abortRef.current?.abort();
const controller = new AbortController();
abortRef.current = controller;
const id = ++requestId.current;
setLoading(true);
setStatus('loading');
setError(null);
try {
const res = await fetch(url, {
...requestInit,
...init,
signal: controller.signal,
});
setResponse(res);
if (!res.ok) {
throw new Error(`Request failed with status ${res.status}`);
}
const parsed = await parser(res);
if (!isMounted() || id !== requestId.current) return undefined;
setData(parsed);
setStatus('success');
setLoading(false);
onSuccess?.(parsed);
return parsed;
} catch (e) {
if ((e as Error).name === 'AbortError') return undefined;
if (!isMounted() || id !== requestId.current) return undefined;
const err = e instanceof Error ? e : new Error(String(e));
setError(err);
setStatus('error');
setLoading(false);
onError?.(err);
return undefined;
}
},
// requestInit is spread; url/enabled/parser drive refetches
[url, enabled, parser, isMounted],
);
useEffect(() => {
if (immediate && url && enabled) {
void refetch();
}
return () => {
abortRef.current?.abort();
};
}, [url, enabled, immediate]);
return { data, error, loading, status, response, refetch, abort };
}
Copy-paste example
useFetch.example.tsx
'use client';
import { useFetch } from '@/hooks';
type User = { id: number; name: string };
export function Users() {
const { data, loading, error, refetch } = useFetch<{ users: User[] }>('/api/users');
if (loading) return <p>Loading…</p>;
if (error) return <p>{error.message}</p>;
return (
<div>
<ul>{data?.users.map((u) => <li key={u.id}>{u.name}</li>)}</ul>
<button onClick={() => void refetch()}>Refresh</button>
</div>
);
}Production checklist
- Called only from Client Components or other custom hooks
- Type parameters filled in (e.g.
useFetch<User[]>) - Tip: Abort in-flight work when the URL changes. Prefer null URL / enabled:false to skip.
- Source of truth: open
hooks/async/useFetch.tsfor implementation details