Skip to Content

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 a Promise, usually a function of useApiClient.
  • options.manual: true skips the call on mount; you call run().
  • options.defaultData: the value of data before the first call.
  • options.refreshDeps: a list of values; when one changes, the hook calls service again.
  • 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: true while a call runs. Starts as true unless manual: true.
  • error: the error of the latest call, or undefined.
  • run(...args): calls service with these arguments. Returns the result; on failure it rethrows after calling onError.
  • refresh(): calls again with the arguments of the previous run.
  • mutate(next): replaces data locally without calling the server. Takes a value or a (prev) => next function.

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

Last updated