Shared state
A small shop with a cart badge in the header, a product grid and a cart panel. The three parts share no props, no
context and no state library. The cart lives in one cache entry: one component fetches it, the others read it with
useCache and change it with client.cache.update().
Opens the example in StackBlitz in a new tab. The first start installs packages and takes a few seconds.
import { createClient } from "@hyper-fetch/core";
export const client = createClient({ url: "https://dummyjson.com" });
export type Product = { id: number; title: string; price: number; thumbnail: string };
export type CartItem = { id: number; title: string; price: number; quantity: number; total: number };
export type Cart = { id: number; products: CartItem[]; total: number; totalQuantity: number };
export const getProductsRequest = client
.createRequest<{ response: { products: Product[] }; queryParams: { limit: number; select: string } }>()({
endpoint: "/products",
})
// `select` is a dummyjson query param: the API returns only these fields.
.setQueryParams({ limit: 6, select: "title,price,thumbnail" });
/**
* One cart, one cache key. Every component that uses this request instance shares the same data.
* The cart is changed in the cache only, so the entry is kept until the page closes (the default is 5 minutes).
*/
export const getCartRequest = client
.createRequest<{ response: Cart }>()({ endpoint: "/carts/:cartId", cacheTime: Infinity })
.setParams({ cartId: 1 });
npx tiged BetterTyped/hyper-fetch/examples/react/shared-state hyper-fetch-react-shared-state && cd hyper-fetch-react-shared-state && npm install && npm run dev- The cache as shared state: every hook that uses the same request reads the same cache entry.
useCachereads that entry without sending a request, here withselectto get only the item count.client.cache.update()changes the entry from anywhere, even outside React, and every reader re-renders.- One fetcher: only
CartPanelcallsuseFetch, so the cart is requested once.
How it works
-
api.tsexports onegetCartRequestinstance with its params set. Its cache key is the shared address of the cart. -
CartPanelcallsuseFetch(getCartRequest). The response is saved in the cache under that key. -
CartBadgesits in the header, far from the panel, and only reads:const { data: count } = useCache(getCartRequest, { select: (cart) => cart.totalQuantity });useCachenever sends a request. Until the panel has loaded the cart,dataisnull. Withselect, the badge re-renders only when the count changes. -
cart.tshasaddToCart()andremoveFromCart(). They callclient.cache.update(getCartRequest, ...)with a function that receives the cached value and returns the changeddata. The cache emits the change and both the badge and the panel update. The functions are plain modules, so a product card can call them without any hook. -
The cart request has
cacheTime: Infinity. The cart is only changed in the cache, and with the default of five minutes the entry would be removed and fetched again from the server, losing the changes.
useCache also returns setData, but it changes only that hook's state. To change what every component sees, write to
the cache with client.cache.update() or client.cache.set().
- Server data that several distant components show or change: the current user, a cart, unread counts, settings.
- For state that never comes from a server, a plain React context or state library is simpler.
- To save the change on the server too, send a mutation with an optimistic update. See the optimistic updates example.
Related
A request's cache key works as a shared address. One component fetches, others read with useCache, and
client.cache.update() changes the data for all of them at once.
