Browser APIs
useFetch
Hook for fetching data from URLs with loading states, error handling, and automatic JSON parsing
useFetch
A hook for fetching data from URLs with proper TypeScript generics, error handling, and automatic JSON parsing. It manages loading states and provides a fetch function for manual data fetching.
Note: This hook does not automatically fetch on mount. You must call the returned startFetch function to trigger the request.
Usage
Advanced Usage
POST Request with Body
DELETE Request
API Reference
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
url | string | Yes | The URL to fetch data from |
options | UseFetchOptions | No | Optional fetch configuration |
Return Value
| Property | Type | Description |
|---|---|---|
data | T | null | The fetched data or null |
loading | boolean | Whether the request is loading |
error | Error | null | Error object if request failed |
startFetch | () => Promise<void> | Function to trigger a fetch |
Options
The options object extends the standard RequestInit interface (excluding signal for compatibility):
| Property | Type | Default | Description |
|---|---|---|---|
method | string | 'GET' | HTTP method |
headers | Record<string, string> | {} | Request headers |
body | string | FormData | URLSearchParams | - | Request body |
cache | RequestCache | 'default' | Cache strategy |
credentials | RequestCredentials | 'same-origin' | Credentials policy |
mode | RequestMode | 'cors' | Request mode |
redirect | RequestRedirect | 'follow' | Redirect policy |
referrer | string | - | Referrer URL |
referrerPolicy | ReferrerPolicy | - | Referrer policy |
integrity | string | - | Subresource integrity |
keepalive | boolean | - | Keep-alive flag |
onSuccess | (data: any) => void | - | Success callback |
onError | (error: Error) => void | - | Error callback |
onFetch | () => void | - | Fetch start callback |
Notes
- This hook does not cache requests - each call triggers a fresh fetch
- The hook does not automatically fetch on mount - you must call the
startFetchfunction - The hook automatically handles JSON parsing of responses
- HTTP errors (4xx, 5xx) are thrown as
Errorobjects withstatusandstatusTextproperties - Network errors are properly caught and exposed through the
errorproperty - The
startFetchfunction returns a Promise that resolves when the request completes - TypeScript generics provide full type safety for the fetched data
- Callbacks are called at appropriate times during the fetch lifecycle:
onFetch: Called when the fetch starts (before the request is made)onSuccess: Called when the request succeeds (with the fetched data)onError: Called when the request fails (with the error object)
Related Hooks
usePromise- Handle promises without loading statesuseAsyncEffect- Async operations in effects