Skip to main content

Prefetching

A product list with a details panel. Hovering or focusing a product starts loading its details, so by the time you click they are in the cache. The details endpoint is slowed down on purpose, and a log shows which requests reach the network.

intermediatesendprefetchingcacheuseFetch
import { useFetch } from "@hyper-fetch/react";
import { useEffect, useState } from "react";

import { client, getProducts, productDetails } from "./api";

const ProductDetails = ({ productId }: { productId: number }) => {
// `revalidate: false`: a fresh cached product renders without asking the server again.
const { data, error, loading } = useFetch(productDetails(productId), { revalidate: false });

if (loading && !data) return <article aria-busy="true">Loading product...</article>;
if (error) return <article>Could not load the product: {error.message}</article>;
if (!data) return null;

return (
<article>
<header>
<h3>{data.title}</h3>
<small className="muted">
${data.price} · {data.brand ?? "No brand"} · rated {data.rating}
</small>
</header>
{data.images[0] && <img src={data.images[0]} alt="" className="cover" />}
<p>{data.description}</p>
</article>
);
};

export const App = () => {
const [selected, setSelected] = useState<number | null>(null);
const [prefetched, setPrefetched] = useState<number[]>([]);
const [log, setLog] = useState<string[]>([]);
// `select` is a dummyjson query param: the API returns only these fields.
const { data, error, loading } = useFetch(getProducts.setQueryParams({ limit: 10, select: "title,price" }));

const prefetch = (productId: number) => {
// Fills the cache in the background. `cache-first` skips the call when the product is cached already.
productDetails(productId).send({
cachePolicy: "cache-first",
onResponse: ({ response }) => {
if (response.success) setPrefetched((ids) => (ids.includes(productId) ? ids : [...ids, productId]));
},
});
};

// Log every request that reaches the network.
useEffect(
() =>
client.requestManager.events.onRequestStart(({ request }) => {
setLog((entries) => [`GET ${request.endpoint}`, ...entries].slice(0, 12));
}),
[],
);

return (
<main className="container">
<hgroup>
<h1>Prefetching</h1>
<p>
Hover a product, then open it. The details are already in the cache. Open one without hovering to compare.
</p>
</hgroup>
<div className="grid-3">
<section>
{loading && !data && <p aria-busy="true">Loading products...</p>}
{error && <p>Could not load products: {error.message}</p>}
<ul className="list">
{data?.products.map((product) => (
<li key={product.id}>
<button
type="button"
className={product.id === selected ? undefined : "outline secondary"}
onMouseEnter={() => prefetch(product.id)}
onFocus={() => prefetch(product.id)}
onClick={() => setSelected(product.id)}
>
{product.title}
{prefetched.includes(product.id) && <mark>prefetched</mark>}
</button>
</li>
))}
</ul>
</section>
{selected ? <ProductDetails productId={selected} /> : <p className="muted">No product selected.</p>}
<article>
<header>
<strong>Network requests</strong>
</header>
<ul className="log">
{log.map((entry, index) => (
<li key={log.length - index}>{entry}</li>
))}
</ul>
</article>
</div>
</main>
);
};
Run locallynpx tiged BetterTyped/hyper-fetch/examples/react/prefetching hyper-fetch-react-prefetching && cd hyper-fetch-react-prefetching && npm install && npm run dev
What it shows
  1. Prefetching is send(). Any request sent outside a hook stores its response in the cache.
  2. One request builder (productDetails) for the prefetch and the hook, so both use the same cache key.
  3. cachePolicy: "cache-first" skips the prefetch when the product is cached already.
  4. staleTime with revalidate: false lets the details view use the prefetched data without a second request.

How it works​

  1. api.ts defines getProduct with staleTime: Time.MIN and a productDetails(productId) helper that sets the params and query params. The delay query param makes the endpoint take about a second.
  2. Each product button calls prefetch(product.id) on onMouseEnter and onFocus, so mouse and keyboard users both get it. prefetch calls productDetails(productId).send({ cachePolicy: "cache-first", onResponse }).
  3. The onResponse callback of send() marks the product as prefetched once the response is in the cache.
  4. ProductDetails calls useFetch(productDetails(productId), { revalidate: false }). The cached data is fresh, so the hook renders it at once and sends nothing. The network log shows a single request per product.
  5. If you click before the prefetch has finished, the hook joins the request already in flight instead of starting a second one, because GET requests are deduplicated.
const prefetch = (productId: number) =>
productDetails(productId).send({ cachePolicy: "cache-first" });

Without revalidate: false, the hook would still render the cached data at once, then refresh it in the background. That is the better choice when the data changes often.

When to use it
  • Lists that open a details view, where hover or focus is a strong hint of the next click.
  • Slow endpoints, where starting a few hundred milliseconds early is noticeable.

Summary

You prefetched details on hover and focus with send(), shared the cache key with the details view through one request builder, and opened prefetched products without a loading state or a second request.