TanStack Router
A product catalog with code-based TanStack Router routes. Route loaders put the data into the HyperFetch cache, and with
defaultPreload: "intent" the router runs a product's loader as soon as you hover or focus its link. The product page
is slowed down on purpose: a hovered product opens at once, a cold one shows the pending screen. A panel lists the
requests that reach the network.
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 { createRootRoute, createRoute, createRouter, Link, Outlet } from "@tanstack/react-router";
import { useSyncExternalStore } from "react";
import { getNetworkLog, productDetails, productList, subscribeNetworkLog } from "./api";
const NetworkLog = () => {
const log = useSyncExternalStore(subscribeNetworkLog, getNetworkLog);
return (
<article>
<header>Requests sent to the network</header>
<ul className="log">
{log.map((line, index) => (
<li key={`${index}-${line}`}>{line}</li>
))}
</ul>
</article>
);
};
const rootRoute = createRootRoute({
component: () => (
<main className="container">
<hgroup>
<h1>Products</h1>
<p>Hover a product: the router runs its loader, and HyperFetch fills the cache before you click.</p>
</hgroup>
<Outlet />
<NetworkLog />
</main>
),
});
const productsRoute = createRoute({
getParentRoute: () => rootRoute,
path: "/",
// The loader only fills the HyperFetch cache. `cache-first` skips the request when the data is cached already.
loader: async () => {
await productList.send({ cachePolicy: "cache-first" });
},
component: () => {
const { data, error } = useFetch(productList, { revalidate: false });
if (error) return <p className="error">Could not load products: {error.message}</p>;
return (
<ul className="products">
{data?.products.map((product) => (
<li key={product.id}>
{/* With `defaultPreload: "intent"`, hovering or focusing this link runs the product loader. */}
<Link to="/products/$productId" params={{ productId: product.id }}>
{product.title}
</Link>{" "}
<small className="muted">${product.price}</small>
</li>
))}
</ul>
);
},
});
const productRoute = createRoute({
getParentRoute: () => rootRoute,
path: "/products/$productId",
// Path params are strings, parse them once so the loader and the component get a number.
params: {
parse: ({ productId }) => ({ productId: Number(productId) }),
stringify: ({ productId }) => ({ productId: String(productId) }),
},
loader: async ({ params }) => {
await productDetails(params.productId).send({ cachePolicy: "cache-first" });
},
pendingComponent: () => <p aria-busy="true">Loading the product (it was not prefetched)...</p>,
component: function ProductPage() {
const { productId } = productRoute.useParams();
const { data, error } = useFetch(productDetails(productId), {
revalidate: false,
});
if (error) return <p className="error">Could not load the product: {error.message}</p>;
if (!data) return null;
return (
<article>
<header>
<Link to="/">Back to products</Link>
<h2>{data.title}</h2>
<small className="muted">
{data.brand ?? "No brand"} · rated {data.rating} · {data.stock} in stock
</small>
</header>
<p>{data.description}</p>
<strong>${data.price}</strong>
</article>
);
},
});
export const router = createRouter({
routeTree: rootRoute.addChildren([productsRoute, productRoute]),
defaultPreload: "intent",
// HyperFetch owns the cache and its stale time, so the router should not keep preloaded results itself.
defaultPreloadStaleTime: 0,
// Show the pending component right away instead of after the default delay.
defaultPendingMs: 0,
});
declare module "@tanstack/react-router" {
interface Register {
router: typeof router;
}
}
npx tiged BetterTyped/hyper-fetch/examples/react/tanstack-router hyper-fetch-react-tanstack-router && cd hyper-fetch-react-tanstack-router && npm install && npm run dev- Loaders fill the cache with
send({ cachePolicy: "cache-first" })and return nothing. - Prefetch on intent:
defaultPreload: "intent"runs the loader on hover, so HyperFetch fetches before the click. - HyperFetch owns the cache:
defaultPreloadStaleTime: 0keeps the router from caching loader results itself. - Typed params:
params.parseturns$productIdinto a number for the loader and the component.
How it works
-
src/api.tsexportsproductListandproductDetails(productId). Both requests have a one-minutestaleTime, andproductDetailsaddsdelay: 800, so a cold product page takes almost a second. -
src/router.tsxdefines the routes withcreateRootRouteandcreateRoute, no file-based routing or codegen plugin. Each loader only fills the cache:loader: async ({ params }) => {await productDetails(params.productId).send({ cachePolicy: "cache-first" });}, -
createRouter({ defaultPreload: "intent" })makes every<Link>run its route loader on hover or focus. The loader sends the request, and the response lands in the HyperFetch cache. -
The route components call
useFetch(productDetails(productId), { revalidate: false }). The request is built the same way as in the loader, so the cache key matches and the hook renders the data with no request. -
defaultPreloadStaleTime: 0tells the router not to keep its own copy of preloaded results. It runs the loader again on every preload or navigation, andcache-firstmakes that free while HyperFetch has the data. -
Hover a product and watch the network panel:
GET /products/:productIdappears before you click, and nothing new appears when you open it. Open a product from the address bar instead, and thependingComponentshows while it loads.
- Apps on TanStack Router that want HyperFetch caching, retries and deduplication for loader data.
- Lists of links to slow pages, where prefetching on hover hides the wait.
- Teams that keep one cache for loaders, hooks and mutations instead of the router's built-in loader cache.
Related
TanStack Router loaders call send({ cachePolicy: "cache-first" }) and preload on intent, so HyperFetch has the data
before the click. Components read the same requests with useFetch and render without a loading state.
