Skip to main content

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.

intermediaterouterprefetchingcacheuseFetch
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;
}
}
Run locallynpx tiged BetterTyped/hyper-fetch/examples/react/tanstack-router hyper-fetch-react-tanstack-router && cd hyper-fetch-react-tanstack-router && npm install && npm run dev
What it shows
  1. Loaders fill the cache with send({ cachePolicy: "cache-first" }) and return nothing.
  2. Prefetch on intent: defaultPreload: "intent" runs the loader on hover, so HyperFetch fetches before the click.
  3. HyperFetch owns the cache: defaultPreloadStaleTime: 0 keeps the router from caching loader results itself.
  4. Typed params: params.parse turns $productId into a number for the loader and the component.

How it works​

  1. src/api.ts exports productList and productDetails(productId). Both requests have a one-minute staleTime, and productDetails adds delay: 800, so a cold product page takes almost a second.

  2. src/router.tsx defines the routes with createRootRoute and createRoute, no file-based routing or codegen plugin. Each loader only fills the cache:

    loader: async ({ params }) => {
    await productDetails(params.productId).send({ cachePolicy: "cache-first" });
    },
  3. 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.

  4. 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.

  5. defaultPreloadStaleTime: 0 tells the router not to keep its own copy of preloaded results. It runs the loader again on every preload or navigation, and cache-first makes that free while HyperFetch has the data.

  6. Hover a product and watch the network panel: GET /products/:productId appears before you click, and nothing new appears when you open it. Open a product from the address bar instead, and the pendingComponent shows while it loads.

When to use it
  • 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.

Summary

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.