Skip to main content

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
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 locallynpx tiged BetterTyped/hyper-fetch/examples/react/select hyper-fetch-react-select && cd hyper-fetch-react-select && npm install && npm run dev
What it shows
  1. One request, many readers. Every card calls useFetch(getCart). They share one cache entry and one network call.
  2. select returns the part of the response a component uses, and data gets that type.
  3. Fewer re-renders. A component re-renders only when its selected value changes.
  4. Structural sharing keeps a derived array's reference when its contents are equal, so inline selectors are fine.

How it works​

  1. api.ts defines getCart and updateCart, which changes the cached cart with client.cache.update(). It stands in for a mutation or a realtime event that updates the cache.
  2. ItemCount selects cart.totalQuantity, CartTotal selects cart.total, and ItemNames maps the products to their titles. FullCart has no select.
  3. "Add one of the first item" changes the quantity and the totals. ItemCount, CartTotal and FullCart flash. ItemNames does not, because the titles are the same.
  4. "Rename the first item" changes only a title. ItemNames and FullCart flash, the two totals stay still.
  5. "Refetch from server" brings back the server's cart, so every card that shows a changed value re-renders.
  6. Toolbar reads loading and error in its own component. The cards do not read loading, 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.

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.