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
API Reference
function useFetch<T>(
url: string,
options?: RequestInit
): {
data: T | null,
loading: boolean,
error: Error | null,
refetch: () => void
}Parameters
| Name | Type | Description |
|---|---|---|
url | string | The URL to fetch data from. |
options | RequestInit | Optional. Standard fetch options (method, headers, etc.). |
Returns
| Name | Type | Description |
|---|---|---|
data | T | null | The fetched data, or null if not yet loaded. |
loading | boolean | true while the request is in flight. |
error | Error | null | Error object if the request failed. |
refetch | () => void | Function 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.