Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 38 ยท Suspense and Prefetching

Server Rendering and Hydration

Prefetch on the server and hand the cache to the browser with dehydrate and HydrationBoundary. Covers a per-request QueryClient, staleTime and the Next.js app router pattern.

Everything so far happened in the browser: the page loads, JavaScript runs, requests start, spinners show. With server rendering (SSR) or static generation, the server renders HTML that already contains the data. The visitor sees content at once and search engines read it. Then the browser hydrates: React attaches to the HTML, and TanStack Query needs the same data in its cache, or it would refetch everything and flash spinners.

The mechanism is simple: the server fetches into its own QueryClient, dehydrates the cache into plain JSON, ships it with the page, and the browser hydrates it into the client's cache. This lesson explains each step. A framework and a Node server cannot run in this page, so the framework code is read-only, and the live examples demonstrate the dehydrate and hydrate calls with the core library.

The flow

sequenceDiagram
  participant B as Browser
  participant S as Server
  participant API as API
  B->>S: GET /posts
  S->>API: prefetchQuery(posts)
  API-->>S: data
  S->>S: dehydrate(queryClient)
  S-->>B: HTML + dehydrated JSON
  B->>B: hydrate into new QueryClient
  B->>B: useQuery(posts) finds data, no spinner

The cache travels as JSON inside the page, so the first render on the client matches the server HTML.

Dehydrate and hydrate by hand

dehydrate(queryClient) returns a serializable object listing the queries (key, data, state). hydrate(queryClient, dehydratedState) loads it into another client. In React you rarely call hydrate yourself because HydrationBoundary does it.

JS Move a cache between two clients

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

No output.

By default dehydrate includes only successful queries, so the failed one is left out (the second console.log prints false): the browser will simply try that request itself. Data must be JSON-serializable. Dates become strings, undefined disappears, and class instances become plain objects. Return plain data from query functions, or configure a custom serializer.

Next.js app router pattern (read-only)

These files need a Next.js server, so they are shown, not run.

JSX
// app/providers.jsx  (client component)
"use client";
import { QueryClient, QueryClientProvider, isServer } from "@tanstack/react-query";

function makeQueryClient() {
  return new QueryClient({
    defaultOptions: { queries: { staleTime: 60 * 1000 } },
  });
}
let browserQueryClient;
function getQueryClient() {
  if (isServer) return makeQueryClient();                 // new client per request
  if (!browserQueryClient) browserQueryClient = makeQueryClient(); // one per browser tab
  return browserQueryClient;
}

export default function Providers({ children }) {
  const queryClient = getQueryClient();
  return <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>;
}
JSX
// app/posts/page.jsx  (server component)
import { dehydrate, HydrationBoundary, QueryClient } from "@tanstack/react-query";
import Posts from "./posts";

export default async function PostsPage() {
  const queryClient = new QueryClient();
  await queryClient.prefetchQuery({ queryKey: ["posts"], queryFn: getPosts });

  return (
    <HydrationBoundary state={dehydrate(queryClient)}>
      <Posts />
    </HydrationBoundary>
  );
}
JSX
// app/posts/posts.jsx  (client component)
"use client";
import { useQuery } from "@tanstack/react-query";

export default function Posts() {
  const { data } = useQuery({ queryKey: ["posts"], queryFn: getPosts });
  return <ul>{data.map((p) => <li key={p.id}>{p.title}</li>)}</ul>;
}

The server component fetches and dehydrates; HydrationBoundary hydrates the state into the client's cache; the client component's useQuery finds the data at once.

Rules that prevent leaks and bugs

  1. A new QueryClient per server request. A shared module-level client would serve one user's cached data to another. In the browser, reuse a single client; the helper above does both.
  2. Set a staleTime above zero (for example 60 seconds). With the default of 0, hydrated data is stale the moment it arrives, and the client refetches it immediately, wasting the server's work.
  3. The query key and function must match between server prefetch and client hook. Use shared queryOptions modules.
  4. Do not prefetch private data into a cached page. The dehydrated JSON is part of the HTML. If a CDN caches that page, everyone sees it (this site's own rule: cached pages must be identical for all users).
  5. Prefetch only what appears in the first render. Everything else can load on the client.

Streaming with Suspense (React 19 and Next.js)

Awaiting every prefetch delays the whole page. With streaming you can start a prefetch without awaiting it, and the pending promise is dehydrated and finished later while HTML streams:

JSX
queryClient.prefetchQuery({ queryKey: ["posts"], queryFn: getPosts }); // no await
return (
  <HydrationBoundary state={dehydrate(queryClient)}>
    <Posts />   {/* uses useSuspenseQuery */}
  </HydrationBoundary>
);

This needs the dehydrate option shouldDehydrateQuery to include pending queries (the default in recent versions does for useSuspenseQuery setups; check the docs for your version) and a Suspense boundary around Posts. The browser receives the shell first and the data streams in when ready.

Static generation and other frameworks

The same three tools appear everywhere: Remix and React Router loaders return dehydrate(queryClient), TanStack Start and Router put queryClient in the router context, Astro and static builds prefetch at build time (set staleTime to match how often content changes). Even without SSR, you can ship an initial cache snapshot as initialData for a handful of queries.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does dehydrate(queryClient) return?

    It produces plain data (queries with keys and states) that can be embedded in HTML and given to hydrate later.
  2. 2. Why create a new QueryClient for each server request?

    Server module state lives across requests, so a shared cache can mix users' data.
  3. 3. Why set staleTime above 0 when hydrating?

    A positive staleTime tells the client the server-fetched data is fresh enough to use as is.
  4. 4. Which queries does dehydrate include by default?

    Failed queries are skipped so the browser retries them itself.

Summary

  • The server prefetches, dehydrate serializes the cache, and the browser hydrates it (via HydrationBoundary).
  • Use one QueryClient per server request and one per browser tab.
  • Set staleTime above zero so hydrated data is not refetched at once.
  • Share queryOptions between server and client, and never put private data in cacheable HTML.
  • Unawaited prefetches plus Suspense enable streaming.

Next: Router Loaders and Waterfalls