Rest Hooks
Normalized state management for async data. Safe. Fast. Reusable.
README
Rest hooks
Define your async methods. Use them synchronously in React. Instantly mutate the data and automatically update all usages.
Installation
- ```bash
- npm install @rest-hooks/react @rest-hooks/rest @rest-hooks/test
- ```
For more details, see the Installation docs page.
Usage
Simple TypeScript definition
- ```typescript
- class User extends Entity {
- id = '';
- username = '';
- pk() {
- return this.id;
- }
- }
- class Article extends Entity {
- id = '';
- title = '';
- body = '';
- author = User.fromJS();
- pk() {
- return this.id;
- }
- static schema = {
- author: User,
- }
- }
- ```
Create collection of API Endpoints
- ```typescript
- const UserResource = createResource({
- path: '/users/:id',
- schema: User,
- });
- const ArticleResource = createResource({
- path: '/articles/:id',
- schema: Article,
- });
- ```
One line data binding
- ```tsx
- const article = useSuspense(ArticleResource.get, { id });
- return (
- <>
- <h2>{article.title} by {article.author.username}</h2>
- <p>{article.body}</p>
- </>
- );
- ```
- ```tsx
- const ctrl = useController();
- return (
- <ProfileForm
- onSubmit={data => ctrl.fetch(UserResource.update, { id }, data)}
- />
- );
- ```
- ```tsx
- const price = useLive(PriceResource.get, { symbol });
- return price.value;
- ```
- ```tsx
- const sortedArticles = new Query(
- new schema.All(Article),
- (entries, { asc } = { asc: false }) => {
- const sorted = [...entries].sort((a, b) => a.title.localeCompare(b.title));
- if (asc) return sorted;
- return sorted.reverse();
- }
- );
- const articlesUnsorted = useCache(sortedArticles);
- const articlesAscending = useCache(sortedArticles, { asc: true });
- const articlesDescending = useCache(sortedArticles, { asc: false });
- ```
...all typed ...fast ...and consistent
For the small price of 9kb gziped. 🏁Get started now
Features
- [x]
Strong Typescript inference
- [x] 🛌 React Suspense support
- [x] 🧵 React 18 Concurrent mode compatible
- [x] 🎣 Declarative API
- [x] 📝 Composition over configuration
- [x] 💰 Normalized caching
- [x] 💥 Tiny bundle footprint
- [x] 🛑 Automatic overfetching elimination
- [x] ✨ Optimistic updates
- [x] 🧘 Flexible to fit any API design (one size fits all)
- [x] 🔧 Debugging and inspection via browser extension
- [x] 🌳 Tree-shakable (only use what you need)
- [x] 🔁 Subscriptions
- [x] ♻️ Optional redux integration
- [x] 📙 Storybook mocking
- [x] 📱 React Native support
- [x] ⚛️ NextJS support
- [x] 🧅 Composable middlewares
- [x] 💽 Global data consistency guarantees
- [x] 🏇 Automatic race condition elimination
- [x] 👯 Global referential equality guarantees