T
TanStack•3y ago
like-gold

Why do we create several QueryClients when using SSR?

I was reading on using SSR in Nextjs, and following the guide, we first define the QuerClient Provider in a client component, and wrap our app in it like usual.
"use client";
export default function Providers({ children }: { children: ReactNode }) {
const [queryClient] = useState(() => new QueryClient());

return (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
);
}
"use client";
export default function Providers({ children }: { children: ReactNode }) {
const [queryClient] = useState(() => new QueryClient());

return (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
);
}
Then in a page, we create a server component like so
export default async function PostsPage() {
const queryClient = new QueryClient()
await queryClient.prefetchQuery({ queryKey: ['posts'], queryFn: getPosts });

return (
<HydrationBoundary state={dehydrate(queryClient)}>
<Posts />
</HydrationBoundary>
)
}
export default async function PostsPage() {
const queryClient = new QueryClient()
await queryClient.prefetchQuery({ queryKey: ['posts'], queryFn: getPosts });

return (
<HydrationBoundary state={dehydrate(queryClient)}>
<Posts />
</HydrationBoundary>
)
}
It seems to me like there is one QueryClient on the client, and several on the server. We need to define a new QueryClient for each component that uses refetch. Why can't the server use a single instance of QueryClient?
2 Replies
middle-aqua
middle-aqua•3y ago
Up 🫠 how to use isLoading, and Error when using
export default async function PostsPage() {
const queryClient = new QueryClient()
await queryClient.prefetchQuery({ queryKey: ['posts'], queryFn: getPosts });

return (
<HydrationBoundary state={dehydrate(queryClient)}>
<Posts />
</HydrationBoundary>
)
}
export default async function PostsPage() {
const queryClient = new QueryClient()
await queryClient.prefetchQuery({ queryKey: ['posts'], queryFn: getPosts });

return (
<HydrationBoundary state={dehydrate(queryClient)}>
<Posts />
</HydrationBoundary>
)
}
yelping-magenta
yelping-magenta•3y ago
Why can't the server use a single instance of QueryClient?
you can, but then the cache gets shared between users and requests, which is rarely what you want. As the docs suggest, you can wrap the client creation in cache() from react to make it request scoped, but another disadvantage is that each HydrationBoundary will then dehydrate the whole client so some things might be sent multiple times. all of this should be in the docs

Did you find this page helpful?