Course contentsShow
← React
Lesson 1820 of 2,39642. Data Fetching LibrariesFree lesson

Prefetching tRPC Queries on the Server

Using createServerSideHelpers to prefetch queries during SSR/SSG; hydrating TanStack Query's cache for instant data.

Prefetching tRPC Queries on the Server

What you'll learn: How to prefetch tRPC queries during server-side rendering so data is already in the cache when your React app hydrates.

The Problem: Waterfalls and Loading States

When using tRPC queries in a client-side React app, users see loading spinners while data fetches. With server-side rendering (SSR) or static site generation (SSG), you can fetch data on the server and send fully-rendered HTML to the browser — but you still need to "hydrate" TanStack Query's cache so the client doesn't refetch unnecessarily.

The Solution: createServerSideHelpers

tRPC provides createServerSideHelpers to prefetch queries on the server. Think of it as a "preview pass" — the server runs your queries, populates TanStack Query's cache, then serializes that cache to send along with the HTML.

How it works:

  1. Server-side: Call createServerSideHelpers with your tRPC router and context
  2. Fetch data: Use helpers.users.getAll.prefetch() to run queries
  3. Serialize cache: Call helpers.dehydrate() to extract the cache state
  4. Pass to client: Send the dehydrated state as props to your page component
  5. Client-side: Wrap your app with <HydrationBoundary state={dehydratedState}> so TanStack Query rehydrates the cache

The magic: When your component first renders on the client, trpc.users.getAll.useQuery() finds the data already in cache — no loading state, no extra network request. The user sees instant content.

This pattern combines the SEO and performance benefits of SSR with the interactive benefits of client-side React, all while maintaining end-to-end type safety.

Key Takeaway: Use createServerSideHelpers to prefetch tRPC queries during SSR/SSG and hydrate TanStack Query's cache for instant, spinner-free data on first render.