Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 38 ยท Suspense and Prefetching

Prefetching and Initial Data

Make screens feel instant with TanStack Query: prefetchQuery on hover, ensureQueryData, initialData from other caches, placeholderData, and when to use each one.

The fastest request is the one the user never waits for. TanStack Query gives you several ways to have data ready before a component asks for it, or to show something real while the true data loads. They look alike, and mixing them up is a common source of bugs, so this lesson sorts them out: prefetchQuery, ensureQueryData, initialData and placeholderData.

prefetchQuery: warm the cache early

queryClient.prefetchQuery runs a query and stores the result in the cache without any component observing it. It returns a promise that never rejects (errors are swallowed; the real useQuery will show them later), and it respects staleTime: if fresh data is already cached, no request is made.

JavaScript
const queryClient = useQueryClient();

<a
  href={"/products/" + id}
  onMouseEnter={() =>
    queryClient.prefetchQuery({
      queryKey: ["product", id],
      queryFn: () => fetchProduct(id),
      staleTime: 60_000,
    })
  }
>

Hovering takes a few hundred milliseconds before the click, enough for many requests. When the product page mounts, useQuery with the same key finds the data and renders immediately.

Without a staleTime the prefetched data is stale at once, so the page's useQuery would refetch on mount in the background. That is not wrong, but you save a request by giving prefetched queries a short staleTime.

Prefetch on hover

Hover a button for a second and click: the page opens with no loading text. Click another one without hovering and you see "Loading...". Notice productOptions(id): one function holds the key, function and options, and both the hook and the prefetch use it, so they cannot disagree.

queryOptions: one definition, many uses

TanStack Query v5 formalizes that helper as queryOptions:

JavaScript
import { queryOptions } from "@tanstack/react-query";

export const productOptions = (id) =>
  queryOptions({
    queryKey: ["product", id],
    queryFn: () => fetchProduct(id),
    staleTime: 60_000,
  });

useQuery(productOptions(7));
useSuspenseQuery(productOptions(7));
queryClient.prefetchQuery(productOptions(7));
queryClient.getQueryData(productOptions(7).queryKey);

The wrapper is an identity function at runtime; its value is typing (in TypeScript, getQueryData knows the return type from the key) and a single source of truth. Put these definitions in a module per feature.

ensureQueryData: use the cache if you have it

prefetchQuery fetches when stale. ensureQueryData is for code that needs the data now and wants to return it: if the cache has data (stale or not, unless you pass revalidateIfStale: true), it resolves immediately with it; otherwise it fetches and returns. It is perfect for route loaders (covered in Router Loaders).

Method Cache hit Cache miss Rejects on error
prefetchQuery Fetches only if stale Fetches No
fetchQuery Fetches only if stale, returns data Fetches, returns data Yes
ensureQueryData Returns cached data at once Fetches, returns data Yes
JS prefetch, fetch and ensure compared

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The calls counter tells the story: ensureQueryData never refetches when data exists, prefetchQuery skips fresh data, and fetchQuery throws errors while prefetchQuery does not.

initialData: data you already have

initialData puts a value in the cache as if it had been fetched. Use it when you truly have the final data, for example the list query already fetched every product, so the detail query can start from the list item:

JavaScript
useQuery({
  queryKey: ["product", id],
  queryFn: () => fetchProduct(id),
  initialData: () =>
    queryClient.getQueryData(["products"])?.find((p) => p.id === id),
  initialDataUpdatedAt: () =>
    queryClient.getQueryState(["products"])?.dataUpdatedAt,
})

Rules:

  • The query is not pending: status is success immediately.
  • The data is subject to staleTime. With the default staleTime: 0 it refetches right away; set a staleTime if the initial data is good enough.
  • initialDataUpdatedAt tells the library how old the data is, so staleness is measured from the real fetch time of the list, not from "now".
  • If the function returns undefined, the query behaves as if there was no initial data.

placeholderData: data to show, not to keep

placeholderData is shown while the query is pending but is never written to the cache. The query stays pending-like (isPlaceholderData is true) and fetches normally. Use it for approximations: the title from a list while the full article loads, or keepPreviousData for pagination.

JavaScript
useQuery({
  queryKey: ["article", id],
  queryFn: () => fetchArticle(id),
  placeholderData: () => {
    const summary = queryClient.getQueryData(["articles"])?.find((a) => a.id === id);
    return summary && { ...summary, body: "" };
  },
})

Which one to choose

Need Tool
Start loading before navigation prefetchQuery
A loader that returns data or reuses the cache ensureQueryData
Final data from another source (server render, other cache) initialData
A temporary, partial stand-in placeholderData
Keep the last page visible placeholderData: keepPreviousData

A good test: would this value be correct to keep if the request never finished? Yes: initialData. No: placeholderData.

JS initialData and placeholderData differ

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The placeholder was never in the cache and was replaced by the real fetch; the initial data was in the cache and, being fresh, never refetched.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does prefetchQuery do when the cache holds fresh data?

    prefetchQuery respects staleTime: fresh data means no request.
  2. 2. What is the key difference between initialData and placeholderData?

    initialData is treated as real, cached data. placeholderData is only displayed while the query loads.
  3. 3. Which method resolves immediately with cached data and only fetches on a cache miss?

    ensureQueryData is designed for loaders that want data now, reusing the cache if possible.
  4. 4. Why set staleTime on a prefetched query?

    With the default staleTime of 0 the prefetched data counts as stale, so useQuery refetches in the background on mount.

Summary

  • prefetchQuery warms the cache (on hover, in loaders); give it a staleTime.
  • ensureQueryData returns cached data or fetches; fetchQuery always respects staleness and throws on errors.
  • initialData is real cached data (use initialDataUpdatedAt and staleTime); placeholderData is display-only.
  • Share definitions with queryOptions so hooks, prefetches and loaders use one key and function.

Next: Server Rendering and Hydration