Installation
Rest Hooks is a library for fetching structured data in a performant way with no boilerplate.
Its interface is declarative and minimal. A small structure declaration is all that is needed for Rest Hooks to perform numerous fetching and caching optimizations while providing predictable, precisely-typed data to consume.
Structured data means data composed of Objects (maps) and Arrays (lists), as opposed to media like images and videos. This makes it great for API calls regardless of form (REST-like, GraphQL, gRPC), serialization (JSON, YAML), or transport (HTTP, WebSockets, local).
Install rest-hooks
Install the rest-hooks package into your project using yarn
yarn add rest-hooks @rest-hooks/rest
npm install rest-hooks @rest-hooks/rest
TypeScript is optional, but requires at least version 3.7 for full type enforcement.
Legacy (IE) browser support
If you see Uncaught TypeError: Class constructor Resource cannot be invoked without 'new'
,
follow the instructions to add legacy browser support to packages
With most tooling this won't be necessary.
Add provider at top-level component
index.tsx
import { CacheProvider } from 'rest-hooks';
import ReactDOM from 'react-dom';
ReactDOM.render(
<CacheProvider>
<App />
</CacheProvider>,
document.body
);
import { CacheProvider } from 'rest-hooks';
import ReactDOM from 'react-dom';
ReactDOM.createRoot(document.body).render(
<CacheProvider>
<App />
</CacheProvider>
);
import { CacheProvider } from 'rest-hooks';
import { AppRegistry } from 'react-native';
const Root = () => (
<CacheProvider>
<App />
</CacheProvider>
);
AppRegistry.registerComponent('MyApp', () => Root)
Alternatively integrate state with redux
Add Suspense and ErrorBoundary
Suspense will show a fallback while content is loading.
Put the <Suspense/>
component around the point where you want the fallback to be shown.
Any usage of the hooks will need to be below this point in the tree.
Feel free to hook up multiple <Suspense/>
points if you want to show loaders at different
points in your application.
<NetworkErrorBoundary/>
will handle fallbacks upon any network errors.
App.tsx
import { Suspense, memo } from 'react';
import { NetworkErrorBoundary } from 'rest-hooks';
const App = memo(() => (
<div>
<h1>Main Title</h1>
<Nav />
<Suspense fallback={<Spinner />}>
<NetworkErrorBoundary>
<Routes />
</NetworkErrorBoundary>
</Suspense>
</div>
));