Skip to content

useFetch()

useFetch<T>(url): object

Defined in: hooks/async/useFetch.ts:42

A React hook to fetch JSON data from a URL and manage its loading, error, and data state. It is built on top of useAsync and will:

  • Fetch once on mount.
  • Refetch whenever the url changes.
  • Ignore results from outdated requests when multiple fetches are in flight.
  • Avoid updating state after the component has unmounted.

Type Parameters

T

T

The type of the JSON payload returned by the API.

Parameters

url

string

The URL to fetch from.

Returns

object

An object containing:

  • data: The parsed JSON response, or null if not yet loaded or on error.
  • error: An Error instance if the fetch failed.
  • loading: Whether a fetch request is currently in progress.

data

data: T | null

error

error: Error | null

loading

loading: boolean

Example

tsx
import { useFetch } from '@zl-asica/react';

const MyComponent = () => {
  const { data, error, loading } = useFetch<{ message: string }>(
    'https://api.example.com/endpoint'
  );

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error: {error.message}</p>;

  return <p>Data: {data?.message}</p>;
};

Released under the MIT License.