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 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
npm install rest-hooks
Include polyfill (optional IE support)
Rest-hooks is built to be compatible with old browsers, but assumes polyfills will already be loaded. If you want to support old browsers like Internet Explorer, you'll need to install core-js and import it at the entry point of your bundle.
yarn add core-js
npm install core-js
index.tsx
import 'core-js/stable';
// place the above line at top
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
);
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 } from 'react';
import { NetworkErrorBoundary } from 'rest-hooks';
const App = () => (
<div>
<h1>Main Title</h1>
<Nav />
<Suspense fallback={<Spinner />}>
<NetworkErrorBoundary>
<Routes />
</NetworkErrorBoundary>
</Suspense>
</div>
);