HooksuseFetch

useFetch()

The useFetch() hook provides a declarative way to fetch data from APIs. It encapsulates the boilerplate logic for handling async requests, including loading indicators, error catching, and request cancellation cleanup.

Import

typescript
import { useFetch } from 'the-react-hooks';

Usage

Click a button to start fetching
Component.tsx
import { useFetch } from 'the-react-hooks';

interface User {
  id: number;
  name: string;
}

export const Component = () => {
  const { data, error, isLoading } = useFetch<User>(
    'https://jsonplaceholder.typicode.com/users/1'
  );

  if (isLoading) return <p>Loading...</p>;
  if (error) return <p>Error: {error.message}</p>;
  if (!data) return null;

  return (
    <div>
      <h1>User: {data.name}</h1>
      <p>ID: {data.id}</p>
    </div>
  );
}

API

Arguments

  • url string | undefined The URL to fetch data from. If undefined, the request will pause (idle state).
  • options RequestInit (Optional) Standard Fetch API options (method, headers, body, etc.).

Returns

Returns a state object with the following properties:
  • data T | undefined The data received from the API response (parsed as JSON).
  • error Error | undefined Error object if the request failed or the response status was not OK.
  • isLoading boolean True while the request is in progress.