Using TanStack Query Prefetching with React Server Components in Next.js v13
CREATED: 2023 / 07 / 30 Sun
UPDATED: 2023 / 07 / 30 Sun
React Server Components Become Standard in Next.js v13
From Next.js v13, the App Router is Recommended, and React Server Components (RSC) are available by default. Put simply, RSC partially renders the React side on the server and assembles the rest on the client. This reduces the size of JS delivered to the client and speeds up processing.
One advantage of building React on the server side is that you can directly access data sources like databases, reducing network bottlenecks. That said, if you’re still making requests to a separately running server, network round-trips do occur — but the path triggered by client-side user interactions can be cut.
When you don’t need server-specific processing, rendering on the client is fine.
Basically, you’d add a use client declaration to manage state on the client when the component involves user interaction or you want more dynamic UX improvements.
Prefetch on the Server, Use on the Client
Now that we understand RSC, if we’re fetching server data in a server component, it’s meaningless if we can’t use it. So let’s think about how to fetch data in a server component using TanStack Query and use it on the client. Suspense became stable in React 18, and combining it with a loading screen until data is ready would be even better.
Here’s what I’ll cover:
- How to prefetch data on the RSC server component side using TanStack Query
- Using `initialData`
- Using `<Hydrate>`
- How to display a loading screen using Suspense
For client-side data fetching, you can create a GET function via Route Handlers and call it from a client component.
Creating a Project with Next.js v13
First, create a Next.js project.
$ npx create-next-app@latest
✔ What is your project named? … next-13-tanstack-query-prefetching
✔ Would you like to use TypeScript? … No / Yes # Yes
✔ Would you like to use ESLint? … No / Yes # Yes
✔ Would you like to use Tailwind CSS? … No / Yes # Yes
✔ Would you like to use `src/` directory? … No / Yes # Yes
✔ Would you like to use App Router? (recommended) … No / Yes # Yes
✔ Would you like to customize the default import alias? … No / Yes # No
Open the created directory in your editor and start it with npm run dev.
Before doing this, I got a SyntaxError: Unexpected token '??=' error, and couldn’t figure out why.
In my case it was because my Node.js version was too old (v18 works, but I was using v14).
You probably won’t hit the same error, but I’m leaving a note just in case.
Next, install TanStack Query.
$ npm i @tanstack/react-query
For the API, I’ll use PokeAPI again, same as with Flutter.
We’ll call this resource:
https://pokeapi.co/api/v2/pokemon
This lets us fetch a list of Pokémon starting from Bulbasaur.
Let’s create a function to call the API.
There are two approaches to prefetching on server components with TanStack Query:
passing initialData as props to a client component, or using <Hydrate>.
For either approach, first do the setup.
You need to place QueryClientProvider higher up to provide the QueryClient that TanStack Query uses internally.
// Setup
// app/providers.tsx
'use client'
import { useState, ReactNode } from 'react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
export default function Providers({ children }: { children: ReactNode }) {
const [queryClient] = useState(() => new QueryClient())
return (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
)
}
// app/layout.tsx
import Providers from './providers'
import { ReactNode } from 'react'
export default function RootLayout({
children,
}: {
children: ReactNode
}) {
return (
<html lang="en">
<head />
<body>
<Providers>{children}</Providers>
</body>
</html>
)
}
Using initialData
Create app/api/index.ts and call the API inside it.
The directory doesn’t matter.
// app/api/index.ts
export async function fetchPokemons() {
const res = await fetch('https://pokeapi.co/api/v2/pokemon', {
headers: { 'Content-Type': 'application/json' },
})
const data = await res.json()
return data
}
Here I assume the API is provided by a separate server, but fetchPokemons could also access a database directly — that’s fine too.
It would also be nice to have a data-shaping step in this layer that formats the data in a consistent way for all components (e.g., wrapping it in an object with metadata and pagination info).
Call this function from app/components/page.tsx (a server component).
// app/components/page.tsx
import { fetchPokemons } from '../api/index'
import Pokemons from './pokemons/page'
export default async function Pokemon() {
const initialData = await fetchPokemons()
return <Pokemons pokemons={initialData} />
}
The client component <Pokemons /> is created in app/components/pokemons/page.tsx as follows.
// app/components/pokemons/page.tsx
'use client'
import { useQuery } from '@tanstack/react-query'
import { fetchPokemons } from '../../api/index'
export default function Pokemons(props: { pokemons: any }) {
const { data } = useQuery({
queryKey: ['pokemons'],
queryFn: fetchPokemons,
initialData: props.pokemons,
})
// Extract data from data
return (
<section className="w-[400px]">
<p>Prefetch via initialData</p>
{data.results.map((result: { name: string }) => (
<dl key={result.name} className="h-[120px]">
<dt>
<p>{result.name}</p>
</dt>
<dd>DESCRIPTION</dd>
</dl>
))}
</section>
)
}
We can now output the data fetched in the server component to the client component.
The Pokémon list is in data.results and can be spread with map.
Using <Hydrate>
According to the official docs, it caches the QueryClient.
This creates a QueryClient that is a singleton scoped to the request, preventing it from being shared between different users or requests.
This is called in a server component described below and is created only once per request.
// app/getQueryClient.tsx
import { QueryClient } from '@tanstack/react-query'
import { cache } from 'react'
const getQueryClient = cache(() => new QueryClient())
export default getQueryClient
Use this in app/components/hydrate/pages.tsx to prefetch data with prefetchQuery.
// app/components/hydrate/pages.tsx
import { dehydrate, Hydrate } from '@tanstack/react-query'
import getQueryClient from '../../getQueryClient'
import { fetchPokemons } from '../../api/index'
import Pokemons from './pokemons/page'
export default async function HydratedPosts() {
const queryClient = getQueryClient()
await queryClient.prefetchQuery(['pokemons'], fetchPokemons)
const dehydratedState = dehydrate(queryClient)
return (
<Hydrate state={dehydratedState}>
<Pokemons />
</Hydrate>
)
}
The <Pokemons /> called inside <Hydrate> is a client component.
// app/components/hydrate/pokemons/page.tsx
'use client'
import { useQuery } from '@tanstack/react-query'
import { fetchPokemons } from '../../../api/index'
export default function Pokemons() {
// Can immediately use data prefetched on the server component side
const { data } = useQuery({ queryKey: ['pokemons'], queryFn: fetchPokemons })
// Data can also be fetched this way, but the fetch won't run until rendered on the client
// const { data: otherData } = useQuery({
// queryKey: ['pokemons-2'],
// queryFn: fetchPokemons,
// })
// Extract data from data
return (
<section className="w-[400px]">
<p>Prefetch via Hydrate</p>
{data.results.map((result: { name: string }) => (
<dl key={result.name} className="h-[120px]">
<dt>
<p>{result.name}</p>
</dt>
<dd>DESCRIPTION</dd>
</dl>
))}
</section>
)
}
Data retrieved successfully.
Introducing React 18’s Suspense
All you need to do is import Suspense and use it in layout.tsx.
// app/layout.tsx
import { Suspense } from 'react'
// .
// .
// .
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body className={inter.className}>
<Suspense fallback={<div>Loading...</div>}>
<Providers>{children}</Providers>
</Suspense>
</body>
</html>
)
}
PokeAPI data loads so fast it’s hard to notice, but adding a setTimeout should let you see “Loading…” for the duration.
// app/components/hydrate/page.tsx
import { dehydrate, Hydrate } from '@tanstack/react-query'
import getQueryClient from '../../getQueryClient'
import { fetchPokemons } from '../../api/index'
import Pokemons from './pokemons/page'
import { setTimeout } from 'timers/promises'
export default async function HydratedPosts() {
await setTimeout(5000) // Wait 5 seconds
const queryClient = getQueryClient()
await queryClient.prefetchQuery(['pokemons'], fetchPokemons)
const dehydratedState = dehydrate(queryClient)
return (
<Hydrate state={dehydratedState}>
<Pokemons />
</Hydrate>
)
}
Appendix
The code is in the repository.