useFetch

A React hook for data fetching with loading, error states, and refetch capability.

Overview

useFetch handles the common data fetching pattern with automatic state management for loading and error states. It includes request cancellation via AbortController to prevent memory leaks and race conditions.

Demo

User Explorer

Fetching random user data with loading states and error handling.

Live API Data
loading: trueerror: null

API Reference

function useFetch<T>(
  url: string,
  options?: RequestInit
): {
  data: T | null,
  loading: boolean,
  error: Error | null,
  refetch: () => void
}

Parameters

NameTypeDescription
urlstringThe URL to fetch data from.
optionsRequestInitOptional. Standard fetch options (method, headers, etc.).

Returns

NameTypeDescription
dataT | nullThe fetched data, or null if not yet loaded.
loadingbooleantrue while the request is in flight.
errorError | nullError object if the request failed.
refetch() => voidFunction to manually trigger a new fetch.

Usage Examples

Basic Usage

import { useFetch } from 'react-hooks-ts'
 
function UserProfile({ userId }) {
  const { data, loading, error } = useFetch(`/api/users/${userId}`)
 
  if (loading) return <Spinner />
  if (error) return <Error message={error.message} />
  
  return <Profile user={data} />
}

With Refetch

import { useFetch } from 'react-hooks-ts'
 
function StockPrice({ symbol }) {
  const { data, loading, refetch } = useFetch(`/api/stocks/${symbol}`)
 
  return (
    <div>
      <span>{data?.price}</span>
      <button onClick={refetch}>Refresh</button>
    </div>
  )
}

Features

  • Automatic Loading State - No manual state management needed.
  • 🛑 Request Cancellation - Prevents race conditions with AbortController.
  • 🔄 Refetch Support - Manually trigger new requests when needed.
  • 🧹 Auto Cleanup - Pending requests are cancelled on unmount.
  • 💪 Generic TypeScript - Full type inference for your data.