Skip to main content

useFetch

The useFetch hook is used for data fetching. It works on the client as well as on the server. The data that is fetched on the server will be transferred to the client.

import { useFetch } from '@archibald/client';

const RETURN_VALUE = useFetch<DATA_TYPE>(PARAMETERS);

Besides the positional signature useFetch(key, action, options), the hook also accepts a single options object that combines the key, the action callbacks and the fetch options:

const RETURN_VALUE = useFetch<DATA_TYPE>({
key: ['product', id],
data: async ({ request }) => request.get(`/products/${id}`),
// ...any FetchOptions
ssr: false
});

The object form (FetchMaxOptions<T>) is FetchOptions & DataOptions<T> & { key: FetchKey } — i.e. key is required, the action lives in the data / before / after fields and all fetch options sit on the same object.

Looking for a Suspense-first variant?

If your component cannot render without the data, prefer useSuspenseFetch. It always suspends and always throws errors to the nearest error boundary, so its data is guaranteed present and you can drop the isLoading / isError branches. Both hooks share the same request handling, so a key is fully interchangeable between them.

Parameters

NameTypeRequiredDescription
keyFetchKey✔️
  • The key to uniquely identify the fetched data in the cache.
  • The action will be reexcuted if the key changes.
actionDataFunctionType<DATA_TYPE>✔️
  • The action is a function or an object containing a function that will be executed to request data.
  • Must return a promise that will either resolve data or throw an error or be null.
optionsFetchOptions
  • The options that define the behavior of the useFetch hook.

key

The key can be of type string, number or null, or an array of these types.

The key can also be an object of type KeyObject. The KeyObject object has the following properties:

NameTypeDescription
keyKeyTypeThe key as described above.
groupstring | booleanA group to be used as fallback by the useFetch hook.

action

An action can be a function or an object.

Passing a function as the action

  • Type: DataFunction<DATA_TYPE>

The callback function passed to the useFetch hook receives an object of type DataFunctionParams that provides following properties:

PropertyTypeDescription
clientDataClientThe DataClient instance.
isServerbooleanReturns true when the data fetching takes place on the server.
isFirstRenderbooleanReturns true on the first render.
requestDataRequestThe DataRequest instance.
willFetchbooleanReturns true if the data fetching will take place.
signalAbortSignalAbort signal for this fetch run. It aborts when the run is superseded by a newer one for the same key, when the entry is deleted, or when the client is destroyed. Forward it into your request (e.g. api.createRequest({ url, signal })) to cancel the in-flight network call — a run that rejects because its signal aborted is treated as cancelled, not as an error.

Passing an object as the action

  • Type: DataOptions<DATA_TYPE>

The DataOptions object has the following properties: More Info...

PropertyTypeDescription
afterVoidFunction
  • A function that will be executed after the data function.
  • Receives params of type DataFunctionParams.
beforeVoidFunction
  • A function that will be executed before the data function.
  • Receives params of type DataFunctionParams.
dataDataFunctionSee Passing a function as the action section for reference.
Callbacks stay current across renders

The data, before and after callbacks do not need to be memoized to keep the request stable. useFetch reads the latest closure you pass on every invocation, so changing the action function between renders (for example, one that closes over changed props or state) is reflected in the cache and the UI without recreating the underlying request or re-triggering a fetch. The key still controls when a refetch happens.

Options

  • Type: FetchOptions

The FetchOptions object has the following properties:

NameTypeDefaultDescription
clearOnRefetchbooleantrueDefines if the cache entry should be deleted before being refetched. More Info...
enabledbooleantrue
  • Defines if the useFetch hook is active or not.
  • If this is set to false, the action function will not be executed.
More Info...
enableOnlyWhenAllKeysTruthybooleanfalseIf true, the action will only be executed when all keys resolve to true. More Info...
errornumber5 secondsDefines how long an error is kept in the cache. More Info...
errorBoundarybooleanfalseDefines if the error should be thrown. The suspense property has to be true in order for this to work. More Info...
pollnumber0Reexecute the action in the provided time interval. More Info...
refetchnumber5 minutes
  • Reexecute the action to update the cache entry.
  • The cache entry has to be used at least 1x after the original call of useFetch hook in order to activate this behavior.
More Info...
refetchAfterFocusbooleanfalseReexecute the action when the window regains focus. More Info...
refetchAfterHydratebooleanfalseReexecute the action after the component has been hydrated. More Info...
ssrbooleantrueIf false, the action will only be executed on the client. More Info...
suspendAfterFirstLoadbooleanfalseIf true, the hook only suspends once the request has loaded at least once (or the component has rendered before). When absent, every pending fetch suspends. More Info...
suspensebooleantrueIf true, the useFetch hook will use suspense mode. More Info...
ttlnumber15 minutes
  • Defines how long an entry should be kept in the cache.
  • Use -1 for endless caching.
More Info...
enduringbooleanfalseIf true the cache entry persists throughout automatic cache cleanups after the DataClient cache has reached the maximal amount of entries. More Info...

Return value

  • Type: FetchResult

The FetchResult object has the following properties:

PropertyTypeDescription
dataDATA_TYPE | nullThe data that was retrieved through the hook. This value can be typed by passing a type to the hook. Its reference is kept stable across refetches that return structurally identical data — see structural sharing.
errorDefaultResponseError | nullThe error that was returned in the action.
isLoadingbooleanIndicates if the data is being loaded.
isDonebooleanReturns true when the data is finished loading.
isErrorbooleanReturns true when the request got an error.
isPrefetchedbooleanReturns true when the data was prefetched on the server.
isStalebooleanReturns true when the data was retrieved from cache.
resetErrorFunctionManually clear the error state from the cache and local state. More Info...
refetchFunctionRe-execute the action.
requestDataRequestThe DataRequest instance.
prefetchFunctionExecutes the useFetch hook and puts the data in the cache. The data is not returned.

See also