useRequest
Hook that calls an async function when the component mounts and keeps data, loading and error for rendering.
Usage
app/orders/[id]/page.tsx
import { useParams } from "react-router-dom";
import { Card, Skeleton } from "antd";
import { useApiClient } from "app/api";
import { useRequest } from "app/hooks";
export default function OrderPage() {
const { id } = useParams();
const api = useApiClient();
const { data, loading } = useRequest(() => api.orders.detail(Number(id)), {
refreshDeps: [id], // call again when id changes
});
if (loading) return <Skeleton active />;
return <Card title={`Order ${data?.id}`}>{data?.customerName}</Card>;
}Signature
app/hooks.ts
function useRequest<T>(
service: (...args: any[]) => Promise<T>,
options?: {
manual?: boolean;
defaultData?: T;
refreshDeps?: unknown[];
onSuccess?: (data: T) => void;
onError?: (error: Error) => void;
},
): {
data: T | undefined;
loading: boolean;
error: Error | undefined;
run: (...args: any[]) => Promise<T>;
refresh: () => Promise<T>;
mutate: (next: T | undefined | ((prev: T | undefined) => T | undefined)) => void;
};Parameters
service: a function returning aPromise, usually a function of useApiClient.options.manual:trueskips the call on mount; you callrun().options.defaultData: the value ofdatabefore the first call.options.refreshDeps: a list of values; when one changes, the hook callsserviceagain.options.onSuccess: runs with the result after each successful call.options.onError: runs with the error after each failed call.
These five are the only options. There is no pollingInterval, debounceWait, cacheKey, ready or retryCount.
Returns
data: the result of the latest successful call.loading:truewhile a call runs. Starts astrueunlessmanual: true.error: the error of the latest call, orundefined.run(...args): callsservicewith these arguments. Returns the result; on failure it rethrows after callingonError.refresh(): calls again with the arguments of the previousrun.mutate(next): replacesdatalocally without calling the server. Takes a value or a(prev) => nextfunction.
The automatic call on mount doesn’t throw; read error instead.
Public pages are prerendered at deploy: the automatic call runs once while rendering, so the HTML already holds the data. In the browser the hook starts from that data (no loading state) and refreshes it quietly.
Examples
Reload every 30 seconds:
app/dashboard/page.tsx
const { data, refresh } = useRequest(() => api.reports.today());
useEffect(() => {
const t = setInterval(refresh, 30_000);
return () => clearInterval(t);
}, [refresh]);Search as you type: debounce the input value, then put the debounced value in refreshDeps.
Don’t import useRequest from ahooks: the package isn’t on the allowlist and typecheck fails.
Next steps
- useAction: a button that writes, then calls
refresh. - tableRequest: a list table that loads page by page, no
useRequestneeded. - Call the API from the UI: how pages read and write data, end to end.
Last updated