Skip to content

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.

PropertyTypeRequiredDescription
onLoading(loading: boolean) => voidCalled whenever the loading state toggles.
onError(error: unknown) => voidCalled when the request throws an error (network failure, non-OK response, etc.).
suspensablebooleanWhen true, the hook participates in React's Suspense protocol. The component suspends until the fetch resolves, integrating with &lt;Suspense&gt; and &lt;ErrorBoundary&gt;.

UseFetchResult ​

  • @template T The expected response body type.

Result tuple returned by useFetch.

IndexTypeDescription
[0]T \| undefinedParsed 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]booleantrue while the request is in-flight.
[3]unknownerror — the caught error value when the request fails; undefined otherwise.

Released under the MIT License.