useFetch
See: Fetch API with more control and the possibility to execute request with suspense support.
Demo
INFO
The component uses useFetch hook to call jsonplaceholder API with suspense support and without it.
Loading demo…
Show source code
tsx
import { Suspense } from "react";
import { useFetch } from "../../../..";
export const Delayed = () => {
const [data, callSuspensable] = useFetch("https://jsonplaceholder.typicode.com/comments?id=5", { cache: "no-cache", suspensable: true });
const [data1, call, loading, error] = useFetch("https://jsonplaceholder.typicode.com/comments?id=5", { cache: "no-cache" });
if (loading ) {
return <p>Loading...</p>
}
if (error) {
return <p>Error: {JSON.stringify(error)}</p>
}
return <>
<button onClick={() => callSuspensable()}>Call suspensable</button>
<button onClick={() => call()}>Call</button>
<pre>{JSON.stringify(data??data1, null, 2)}</pre>
</>
}
export const UseFetch = () => {
return <Suspense fallback="loading suspense...">
<Delayed />
</Suspense>
}Types
UseFetchOptions
Options used by useFetch.
| Property | Type | Required | Description |
|---|---|---|---|
onLoading | (loading: boolean) => void | Called whenever the loading state toggles. | |
onError | (error: unknown) => void | Called when the request throws an error (network failure, non-OK response, etc.). | |
suspensable | boolean | When true, the hook participates in React's Suspense protocol. The component suspends until the fetch resolves, integrating with <Suspense> and <ErrorBoundary>. |
UseFetchResult
@templateT The expected response body type.
Result tuple returned by useFetch.
| Index | Type | Description |
|---|---|---|
[0] | T \| undefined | Parsed response data. undefined before the first successful request and after an error. |
[1] | (conf?: RequestInit) => Promise<void> | call — executes the fetch request. Accepts optional per-call RequestInit overrides merged with the hook-level options. |
[2] | boolean | true while the request is in-flight. |
[3] | unknown | error — the caught error value when the request fails; undefined otherwise. |
