Sub topic 17
Server rendering and hydration
This chapter assumes you know the earlier chapters (useQuery, query keys, staleTime) and basic React server rendering. The examples use the Next.js App Router, but the idea applies to any framework that renders React on the server.
The problem
With plain useQuery, the server renders the loading state. The browser then downloads JavaScript, runs the query, and only then shows data. Users see a spinner, and crawlers see no content.
The fix has three steps. The server fetches the data and renders HTML with it. It then sends a serialized copy of the cache along with the HTML. The browser loads that copy into its own QueryClient, so useQuery finds data immediately. Loading the copy is called hydration.
Step 1: a client-side provider
Create the browser QueryClient inside useState, so each user session gets its own instance and it survives re-renders.
'use client'
import { useState, type ReactNode } from 'react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
export function Providers({ children }: { children: ReactNode }) {
const [queryClient] = useState(
() =>
new QueryClient({
defaultOptions: { queries: { staleTime: 60 * 1000 } },
}),
)
return (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
)
}The default staleTime of 0 would make the client refetch right after hydration. A non-zero value keeps the server data fresh for a minute.
Step 2: prefetch and dehydrate on the server
Keep the query function in a plain module so both the server and the client can import it.
// lib/todos.ts
export type Todo = { id: number; title: string; done: boolean }
export async function fetchTodos(): Promise<Todo[]> {
const base = process.env.API_URL ?? 'http://localhost:3000'
const res = await fetch(`${base}/api/todos`)
if (!res.ok) throw new Error(`Request failed: ${res.status}`)
return res.json()
}// app/todos/page.tsx (a Server Component)
import {
dehydrate,
HydrationBoundary,
QueryClient,
} from '@tanstack/react-query'
import { fetchTodos } from '@/lib/todos'
import { Todos } from './todos'
export default async function TodosPage() {
const queryClient = new QueryClient()
await queryClient.prefetchQuery({
queryKey: ['todos'],
queryFn: fetchTodos,
})
return (
<HydrationBoundary state={dehydrate(queryClient)}>
<Todos />
</HydrationBoundary>
)
}Create a new QueryClient for every request on the server. A shared one would leak one user's cached data to another.
Step 3: use the query as usual
// app/todos/todos.tsx
'use client'
import { useQuery } from '@tanstack/react-query'
import { fetchTodos } from '@/lib/todos'
export function Todos() {
const { data } = useQuery({ queryKey: ['todos'], queryFn: fetchTodos })
return (
<ul>
{data?.map((todo) => (
<li key={todo.id}>{todo.title}</li>
))}
</ul>
)
}The query key and function match the prefetch, so the cache entry is found on the first render.
Common errors
- Key mismatch. If the prefetch uses
['todos']and the component uses['todos', 'all'], hydration has no effect and the client fetches again. - Shared server client. Creating
QueryClientat module level on the server shares the cache across requests. - Relative URLs on the server.
fetch('/api/todos')fails outside the browser. Use an absolute URL. - Non-serializable data. Dehydrated state is sent as JSON, so values such as
Dateobjects arrive as strings unless you transform them. - Failed prefetch.
prefetchQuerydoes not throw. The client simply fetches the data itself, so check your server logs if data seems to load late.
Exercise
Your page prefetches ['todos'] on the server, but the browser still shows a loading state and then fires a request. Name two likely causes.
Show answer
The query key in useQuery differs from the one used in prefetchQuery, so the hydrated entry is never matched. Or the server prefetch failed, for example because of a relative URL, so nothing was dehydrated. A third possibility is that the component is not inside a HydrationBoundary that received the dehydrated state.