Select
A shopping cart split into four cards that all read the same cached response. Three of them pick one part of the cart
with select, the fourth reads all of it. Every card flashes when it re-renders, so you can see which ones a change
reaches.
intermediateuseFetchcache
Opens the example in StackBlitz in a new tab. The first start installs packages and takes a few seconds.
import { useFetch } from "@hyper-fetch/react";
import { getCart, updateCart } from "./api";
import { useRenderFlash } from "./use-render-flash";
// Each component sends the same request and shares one cache entry. `select` picks the slice it renders.
const ItemCount = () => {
const ref = useRenderFlash<HTMLElement>();
const { data: count } = useFetch(getCart, { select: (cart) => cart.totalQuantity });
return (
<article ref={ref}>
<small className="muted">select: totalQuantity</small>
<h2>{count ?? "-"} items</h2>
</article>
);
};
const CartTotal = () => {
const ref = useRenderFlash<HTMLElement>();
const { data: total } = useFetch(getCart, { select: (cart) => cart.total });
return (
<article ref={ref}>
<small className="muted">select: total</small>
<h2>${total?.toFixed(2) ?? "-"}</h2>
</article>
);
};
const ItemNames = () => {
const ref = useRenderFlash<HTMLElement>();
// A new array on every run, but structural sharing keeps the old reference while the titles are equal.
const { data: names } = useFetch(getCart, { select: (cart) => cart.products.map((item) => item.title) });
return (
<article ref={ref}>
<small className="muted">select: product titles</small>
<ul>
{names?.map((name) => (
<li key={name}>{name}</li>
))}
</ul>
</article>
);
};
const FullCart = () => {
const ref = useRenderFlash<HTMLElement>();
// No `select`: the component gets the whole response and re-renders on any change.
const { data: cart } = useFetch(getCart);
return (
<article ref={ref}>
<small className="muted">no select: the whole cart</small>
<ul>
{cart?.products.map((item) => (
<li key={item.id}>
{item.quantity} × {item.title}
</li>
))}
</ul>
</article>
);
};
const addOne = () =>
updateCart((cart) => {
const [first, ...rest] = cart.products;
if (!first) return cart;
return {
...cart,
products: [{ ...first, quantity: first.quantity + 1 }, ...rest],
totalQuantity: cart.totalQuantity + 1,
total: cart.total + first.price,
};
});
const rename = () =>
updateCart((cart) => ({
...cart,
products: cart.products.map((item, index) => (index === 0 ? { ...item, title: `${item.title}!` } : item)),
}));
/** Its own component: when `loading` changes, only the toolbar re-renders, not the cards. */
const Toolbar = () => {
const { loading, error, refetch } = useFetch(getCart);
return (
<>
<div className="toolbar">
<button type="button" onClick={addOne}>
Add one of the first item
</button>
<button type="button" className="secondary" onClick={rename}>
Rename the first item
</button>
<button type="button" className="outline secondary" onClick={refetch} aria-busy={loading}>
Refetch from server
</button>
</div>
{error && <p>Could not load the cart: {error.message}</p>}
</>
);
};
export const App = () => (
<main className="container">
<hgroup>
<h1>Select</h1>
<p>Four components read one cached cart. A card flashes when it re-renders.</p>
</hgroup>
<Toolbar />
<div className="cards">
<ItemCount />
<CartTotal />
<ItemNames />
<FullCart />
</div>
</main>
);
Run locally
npx tiged BetterTyped/hyper-fetch/examples/react/select hyper-fetch-react-select && cd hyper-fetch-react-select && npm install && npm run devWhat it shows
- One request, many readers. Every card calls
useFetch(getCart). They share one cache entry and one network call. selectreturns the part of the response a component uses, anddatagets that type.- Fewer re-renders. A component re-renders only when its selected value changes.
- Structural sharing keeps a derived array's reference when its contents are equal, so inline selectors are fine.
How it works
api.tsdefinesgetCartandupdateCart, which changes the cached cart withclient.cache.update(). It stands in for a mutation or a realtime event that updates the cache.ItemCountselectscart.totalQuantity,CartTotalselectscart.total, andItemNamesmaps the products to their titles.FullCarthas noselect.- "Add one of the first item" changes the quantity and the totals.
ItemCount,CartTotalandFullCartflash.ItemNamesdoes not, because the titles are the same. - "Rename the first item" changes only a title.
ItemNamesandFullCartflash, the two totals stay still. - "Refetch from server" brings back the server's cart, so every card that shows a changed value re-renders.
Toolbarreadsloadinganderrorin its own component. The cards do not readloading, so a refetch in progress does not re-render them.
const { data: count } = useFetch(getCart, { select: (cart) => cart.totalQuantity });
useRenderFlash in use-render-flash.ts runs an effect without a dependency array, which fires after every render, and
plays a short outline animation. It is only there to make re-renders visible.
When to use it
- Large responses that several components read in small parts, such as a cart, a settings object or a dashboard.
- Derived values (counts, sums, filtered lists) that should not re-render the component when other fields change.
Related
Summary
You read four views of one cached response with select. Each component re-rendered only when the part it selected
changed, while the request and its cache stayed shared.
