Skip to main content

useFetch()

Fetch without the data rendering.

This can be useful for ensuring resources early in a render tree before they are needed.

tip

Use in combination with a data-binding hook (useCache(), useSuspense(), useDLE(), useLive()) in another component.

Usage

function MasterPost({ id }: { id: number }) {
useFetch(PostResource.get, { id });
// ...
}

Behavior

Expiry StatusFetchReturnsConditions
Invalidyes1Promisenot in store, deletion, invalidation
Staleyes1Promise(first-render, arg change) & expiry < now
Validnoundefinedfetch completion
noundefinednull used as second argument
note
  1. Identical fetches are automatically deduplicated
React Native

When using React Navigation, useFetch() will trigger fetches on focus if the data is considered stale.

Conditional Dependencies

Use null as the second argument to any RDC hook means "do nothing."

// todo could be undefined if id is undefined
const todo = useFetch(TodoResource.get, id ? { id } : null);

Types

function useFetch(
endpoint: ReadEndpoint,
...args: Parameters<typeof endpoint> | [null]
): Promise<any> | undefined;

Examples

Github Reactions

useFetch() allows us to declaratively fetch reactions on any issue page the moment we navigate to it. This allows us to not block the issues page from showing if the reactions are not completed loading.

It's usually better to wrap cases like this in new Suspense Boundaries. However, our component library ant design does not allow this.

More Demos