Getting Started
About
use-remote-data
is a React hook that takes a principled, type-safe approach to fetching and managing async data.
At its core is the RemoteData
union type,
which covers every possible state of a request (from “not yet fetched” to “success with stale data” or “failure”).
On top of this, a RemoteDataStore
automatically handles orchestration — fetching, caching, error handling, invalidation,
and retries—so you can write clear, reliable async code with minimal boilerplate.
It also offers optional typed errors to distinguish between domain-level failures and unexpected runtime issues.
Installation
npm install use-remote-data
yarn add use-remote-data
Basic Usage
The primary entry point is the useRemoteData
hook.
It takes one parameter—a function that produces a Promise
—and returns a RemoteDataStore<T>
.
Because we need the ability to retry, you must pass a function rather than a direct Promise
.
- According to React Hooks rules, the hook must be used inside a component.
- The object returned by
useRemoteData
is ourRemoteDataStore<T>
.
import * as React from 'react';
import {
RemoteDataStore,
useRemoteData,
WithRemoteData,
} from 'use-remote-data';
// all examples will use a fake API like this
function produce<T>(value: T, delayMillis: number): Promise<T> {
return new Promise((resolve) =>
setTimeout(() => resolve(value), delayMillis)
);
}
export const Component: React.FC = () => {
// create a store, which will produce data after a second
const computeOne: RemoteDataStore<number> = //
useRemoteData(() => produce(1, 1000));
// fetch and render
return (
<WithRemoteData store={computeOne}>
{(num: number) => <span>{num}</span>}
</WithRemoteData>
);
};
Rendering with WithRemoteData
In the example above, you can see that the store is passed to a WithRemoteData
component
in order to fetch the data and render it.
One curious possibly unfamiliar thing is that it uses a render prop
that receives your successfully loaded data (along with an isInvalidated
boolean).
Out of the box, WithRemoteData
handles loading and error states but is visually minimal,
including JSON.stringify
ing error objects.
Recommended usage is therefore to copy/paste the WithRemoteData
component into your codebase,
and provide your own rendering for everything.