useFetch
A React hook to abstract the Fetch API with loading, error, and data state management
Installation
Props
Prop | Type | Default | Description |
---|---|---|---|
url | string | undefined | The endpoint URL to fetch data from. |
options? | UseFetchOptions | undefined | Optional Fetch API settings. |
Data
Property | Type | Description |
---|---|---|
data | T | null | The fetched data or null on error. |
error | Error | null | Error object if the request fails. |
loading | boolean | Whether the request is in progress. |
refetch | () => void | Function to re-trigger the fetch request. |
abort | () => void | Cancels the current in-flight request. |
aborted | boolean | Whether 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
- Ensure the
url
parameter is stable or memoized. - Manage authentication headers and tokens via
options
when needed. - 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>
);