Next.js 13+ fundamentally changed how we fetch data with the introduction of React Server Components. At the same time, React Query (TanStack Query) remains the gold standard for client-side caching, mutations, and background revalidation.
Used together correctly, they give you the best of both worlds:
- ⚡ Fast server-rendered pages
- 💾 Intelligent client-side caching
- 🔄 Seamless hydration between server and client
- 🎯 Familiar React Query APIs
This guide walks through battle-tested patterns for combining Server Components with React Query in real-world Next.js applications.
TL;DR
- Prefetch data in Server Components
- Dehydrate the React Query cache on the server
- Hydrate it on the client using
HydrationBoundary - Share query logic using
queryOptions - Handle mutations exclusively on the client
Follow this pattern and your pages will load instantly without losing React Query’s power.
Why Combine Server Components with React Query?
Server Components allow you to fetch data on the server, reducing bundle size and improving initial load times. React Query excels at managing client-side state, caching, mutations, and background updates.
Together, they provide:
- Fast initial loads via server-side data fetching
- Cached data for client-side navigation
- No duplicate network requests after hydration
- A clean separation between server and client concerns
The key is understanding where each responsibility lives.
The Mental Model
Server → Client Data Flow
Server Component (page.tsx)
├─ Prefetch data
├─ Dehydrate query cache
└─ HydrationBoundary
↓
Client Component (component.tsx)
├─ useSuspenseQuery / useQuery
├─ Uses hydrated cache
└─ Handles mutations- The server fetches data once
- The client reuses it from cache
- React Query handles everything after hydration
Step 1: Set Up the React Query Provider
React Query relies on React Context, so your provider must be a Client Component.
"use client"
import {
QueryClient,
QueryClientProvider,
isServer,
} from '@tanstack/react-query'
function makeQueryClient() {
return new QueryClient({
defaultOptions: {
queries: {
staleTime: 60 * 1000, // Prevent immediate refetch after hydration
},
},
})
}
let browserQueryClient: QueryClient | undefined
function getQueryClient() {
if (isServer) {
return makeQueryClient()
}
if (!browserQueryClient) {
browserQueryClient = makeQueryClient()
}
return browserQueryClient
}
export default function Providers({
children,
}: {
children: React.ReactNode
}) {
const queryClient = getQueryClient()
return (
<QueryClientProvider client={queryClient}>
{children}
</QueryClientProvider>
)
}⚠️ Important: Don’t initialise the query client with
useStatewhen using Suspense. React may discard state during the initial render.
Step 2: Centralise Query Logic with queryOptions
This is one of the most important patterns in this guide.
Defining query logic once lets you reuse it on both the server and client — fully typed and consistent.
// features/users/api/users.ts
import { queryOptions } from '@tanstack/react-query'
export interface User {
id: string
name: string
email: string
}
export const getUser = async (userId: string): Promise<User> => {
const response = await fetch(`/api/users/${userId}`)
if (!response.ok) {
throw new Error('Failed to fetch user')
}
return response.json()
}
export const getUserQueryOptions = (userId: string) =>
queryOptions<User>({
queryKey: ['user', userId],
queryFn: () => getUser(userId),
staleTime: 5 * 60 * 1000,
gcTime: 10 * 60 * 1000,
})Why this matters
- Shared query keys
- Type safety everywhere
- No duplicated logic
- Easy testing and refactoring
Step 3: Prefetch Data in Server Components
Server Components (page.tsx) handle the initial fetch.
The trick is to pre-fill React Query’s cache before rendering.
// app/users/[id]/page.tsx
"use server";
import {
QueryClient,
dehydrate,
HydrationBoundary,
} from '@tanstack/react-query'
import { getUserQueryOptions } from '@/features/users/api/users'
import { UserProfile } from '@/features/users/components/UserProfile'
import { Suspense } from 'react'
export default async function Page({
params,
}: {
params: { id: string }
}) {
const queryClient = new QueryClient()
await queryClient.prefetchQuery(
getUserQueryOptions(params.id)
)
return (
<HydrationBoundary state={dehydrate(queryClient)}>
<Suspense fallback={<div>Loading...</div>}>
<UserProfile userId={params.id} />
</Suspense>
</HydrationBoundary>
)
}What’s happening here?
- A new
QueryClientis created per request - Data is fetched on the server
- The cache is dehydrated into JSON
- The client rehydrates it instantly
- No extra network request is made on the clientside
Step 4: Consume Data in Client Components
Client Components use standard React Query hooks.
Because the cache is already hydrated, the data is available immediately.
// features/users/components/UserProfile.tsx
'use client'
import { useSuspenseQuery } from '@tanstack/react-query'
import { getUserQueryOptions } from '../api/users'
export function UserProfile({ userId }: { userId: string }) {
const { data: user } = useSuspenseQuery(
getUserQueryOptions(userId)
)
return (
<div>
<h1>{user.name}</h1>
<p>{user.email}</p>
</div>
)
}💡 If you don’t want Suspense,
useQueryworks the same way—just handle loading and error states manually.
Step 5: Mutations (Client Only)
Mutations always run on the client.
'use client'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { updateUser } from '../api/users'
import { User } from '../api/users'
export function EditUserForm({ user }: { user: User }) {
const queryClient = useQueryClient()
const mutation = useMutation({
mutationFn: updateUser,
onSuccess: (updatedUser) => {
queryClient.setQueryData(
['user', updatedUser.id],
updatedUser
)
},
})
return (
<form
onSubmit={(e) => {
e.preventDefault()
mutation.mutate(user)
}}
>
<button disabled={mutation.isPending}>
Save
</button>
</form>
)
}Another thing I liked about mutations was that you can do asyncronous calls within functions which saves you from going into a useEffect spiral checking if isSuccess is there before doing the next move. For example:
'use client'
import { useEffect } from 'react';
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { updateUser } from '../api/users'
import { User } from '../api/users'
export function EditUserForm({ user }: { user: User }) {
const {mutate isSuccess} = useMutation({
mutationFn: updateUser,
})
useEffect(() => {
if (isSuccess) {
// change some state
}
}, [isSuccess])
return (
<form
onSubmit={(e) => {
e.preventDefault()
mutate(user)
}}
>
<button disabled={mutation.isPending}>
Save
</button>
</form>
)
}You can do it without the useEffect with mutateAsync.
'use client'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { updateUser } from '../api/users'
import { User } from '../api/users'
export function EditUserForm({ user }: { user: User }) {
const {mutateAsync isSuccess} = useMutation({
mutationFn: updateUser,
})
return (
<form
onSubmit={async (e) => {
e.preventDefault()
const data = mutateAsync(user)
if (data) {
// update some state.
}
}}
>
<button disabled={mutation.isPending}>
Save
</button>
</form>
)
}I quite like this approach when you need to chain api calls one of after the other or you want something where you are not too bothered about the state variables that come from the useMutation.
Advanced Patterns (Optional)
Prefetch Multiple Queries in Parallel
You may have multiple query calls that do not depend on each other, this is where you can use promise.all to asynchronously fetch the queries without making the server load time slow.
await Promise.all([
queryClient.prefetchQuery(getUserQueryOptions('me')),
queryClient.prefetchQuery(getNotificationsOptions()),
])Conditional Prefetching
You might want to prefetch a query conditionally.
const user = queryClient.getQueryData<User>(['user', id])
if (user?.isPremium) {
await queryClient.prefetchQuery(
getPremiumFeaturesOptions(id)
)
}Common Mistakes to Avoid
❌ Reusing QueryClient across requests on the server
❌ Initialising the client with useState
❌ Mismatched query keys between server and client
❌ Forgetting to invalidate or update cache after mutations
✅ Always create a new QueryClient on the server
✅ Share queries using queryOptions
✅ Use Suspense where possible
✅ Keep mutations client-side
Final Takeaway
The winning pattern looks like this:
- Server: Prefetch and dehydrate data
- Boundary: Pass state via
HydrationBoundary - Client: Consume with React Query hooks
When done correctly, you get:
- ⚡ Instant page loads
- 🔄 Seamless client navigation
- 💾 Smart caching
- 🎯 Clean, maintainable code
If you’re building serious Next.js apps in 2024+, this pattern is worth mastering.
Originally published on Medium.