h3/use's logo

h3/use

Command Palette

Search for a command to run...

useFetch

A React hook to abstract the Fetch API with loading, error, and data state management

useFetch
Demonstrates the useFetch hook with a 5s artificial delay so you can test the Abort button.

Installation

Props

PropTypeDefaultDescription
urlstringundefinedThe endpoint URL to fetch data from.
options?UseFetchOptionsundefinedOptional Fetch API settings.

Data

PropertyTypeDescription
dataT | nullThe fetched data or null on error.
errorError | nullError object if the request fails.
loadingbooleanWhether the request is in progress.
refetch() => voidFunction to re-trigger the fetch request.
abort() => voidCancels the current in-flight request.
abortedbooleanWhether the request was aborted.

Key Features & Details

  • Generic and type-safe response with TypeScript.
  • Automatic JSON parsing and HTTP error handling.
  • Built-in loading and error state management.
  • Cleanup to prevent state updates on unmounted components.
  • Supports dynamic URL and options updates.

Performance Considerations

  • Avoid passing new options objects on every render to prevent unnecessary refetches.

Best Practices & Caveats

  1. Ensure the url parameter is stable or memoized.
  2. Manage authentication headers and tokens via options when needed.
  3. Use JSON.stringify(options) sparingly for large payloads to avoid overhead.

Examples

Basic GET Request

const { data, error, loading, refetch } = useFetch<Post[]>(
  'https://api.example.com/posts',
);

POST Request

const { data, error, loading } = useFetch<ResponseData>(
  'https://api.example.com/items',
  {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ name: 'New Item' }),
  },
);

Manual Refetch

<Button onClick={refetch}>Refetch Data</Button>

Abort Request

const { loading, abort } = useFetch<any>('https://api.example.com/data');
 
return (
  <Button onClick={abort} disabled={!loading}>
    Abort Request
  </Button>
);