TanStackT
TanStack4mo ago
1 reply
uncertain-scarlet

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>
);


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.
Was this page helpful?