T
TanStack22h ago
fascinating-indigo

Caching prefetched data in a server component

I have some prefetch queries in some of my Next.js server components. I have done this according to docs in "Advanced server rendering".
// Server component
const queryClient = new QueryClient()

await queryClient.prefetchQuery({
queryKey: [
QUERY_KEYS.CLIENTS_STATUS_KPI,
],
queryFn: () =>
getStatusKpi(),
});

const dehydratedState = dehydrate(queryClient);

return (
<HydrationBoundary state={dehydratedState}>
...
</HydrationBoundary>
);
// Server component
const queryClient = new QueryClient()

await queryClient.prefetchQuery({
queryKey: [
QUERY_KEYS.CLIENTS_STATUS_KPI,
],
queryFn: () =>
getStatusKpi(),
});

const dehydratedState = dehydrate(queryClient);

return (
<HydrationBoundary state={dehydratedState}>
...
</HydrationBoundary>
);
I used regular useQuery in client-side with the same query keys and query function. Everything worked fine except the caching part. When I navigate somewhere and navigate back to my page which prefetches this query it seems to trigger my fetch function (getStatusKpi) every single time I navigate. I guess it makes sense cuz the queryClient is created per request. But I have no idea how to still get it cached. It might be Next.js related question, not tanstack query but I need help. Thanks in advance.
0 Replies
No replies yetBe the first to reply to this messageJoin

Did you find this page helpful?