name: lazy-prefetch-pattern description: 'Skill: lazy-prefetch-pattern'
Lazy prefetch pattern (React Query v5 + Next RSC)
Goal: start prefetchQuery() early on the server without awaiting, so it doesn't block SSR / Suspense, while still hydrating on the client.
Requirements (repo-specific)
- QueryClient must dehydrate pending queries.
- In this repo that's in
trpc/query-client.ts:dehydrate.shouldDehydrateQueryincludesquery.state.status === "pending".dehydrate.serializeData/hydrate.deserializeDatause SuperJSON.
- In this repo that's in
Pattern
In a Server Component (e.g. app/(chat)/layout.tsx):
- Create/get the request-scoped query client (
getQueryClient()from@/trpc/server) - Kick off prefetches with
void(no await):void queryClient.prefetchQuery(trpc.foo.bar.queryOptions(...))
- Let
HydrateClient/HydrationBoundarydehydrate the cache.
Use await only for data you must have before rendering (everything else should be lazy-prefetched).