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.



🌎 Website






Installation


  1. ```bash
  2. npm install @rest-hooks/react @rest-hooks/rest @rest-hooks/test
  3. ```

For more details, see the Installation docs page.

Usage



  1. ```typescript
  2. class User extends Entity {
  3.   id = '';
  4.   username = '';

  5.   pk() {
  6.     return this.id;
  7.   }
  8. }

  9. class Article extends Entity {
  10.   id = '';
  11.   title = '';
  12.   body = '';
  13.   author = User.fromJS();

  14.   pk() {
  15.     return this.id;
  16.   }

  17.   static schema = {
  18.     author: User,
  19.   }
  20. }
  21. ```


  1. ```typescript
  2. const UserResource = createResource({
  3.   path: '/users/:id',
  4.   schema: User,
  5. });

  6. const ArticleResource = createResource({
  7.   path: '/articles/:id',
  8.   schema: Article,
  9. });
  10. ```

One line data binding


  1. ```tsx
  2. const article = useSuspense(ArticleResource.get, { id });
  3. return (
  4.   <>
  5.     <h2>{article.title} by {article.author.username}</h2>
  6.     <p>{article.body}</p>
  7.   </>
  8. );
  9. ```


  1. ```tsx
  2. const ctrl = useController();
  3. return (
  4.   <ProfileForm
  5.     onSubmit={data => ctrl.fetch(UserResource.update, { id }, data)}
  6.   />
  7. );
  8. ```


  1. ```tsx
  2. const price = useLive(PriceResource.get, { symbol });
  3. return price.value;
  4. ```


  1. ```tsx
  2. const sortedArticles = new Query(
  3.   new schema.All(Article),
  4.   (entries, { asc } = { asc: false }) => {
  5.     const sorted = [...entries].sort((a, b) => a.title.localeCompare(b.title));
  6.     if (asc) return sorted;
  7.     return sorted.reverse();
  8.   }
  9. );

  10. const articlesUnsorted = useCache(sortedArticles);
  11. const articlesAscending = useCache(sortedArticles, { asc: true });
  12. const articlesDescending = useCache(sortedArticles, { asc: false });
  13. ```


...all typed ...fast ...and consistent


For the small price of 9kb gziped.    🏁Get started now

Features


- [x] TS 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] 🧘 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] 📱 React Native support
- [x] ⚛️ NextJS support
- [x] 💽 Global data consistency guarantees
- [x] 🏇 Automatic race condition elimination
- [x] 👯 Global referential equality guarantees

Examples


- Todo: Source | Sandbox
- Github: Source | Sandbox
- NextJS: Source | Sandbox