Tutorial · Nov 15, 2026 · 9 min read

TanStack Query v5 in Next.js 15: Hydration, Mutations & Infinite Queries

Hands-on patterns for TanStack Query v5 with Next.js 15 App Router. Covers server prefetching, HydrationBoundary, query key factories, optimistic updates, infinite scrolling, Server Action integration

TanStack Query v5 in Next.js 15: Hydration, Mutations & Infinite Queries

Setting Up TanStack Query v5 in a Next.js 15 App Router Project

Begin by creating a fresh Next.js 15 application using the latest template. Run the command:

npx create-next-app@latest my-app \
  --typescript --tailwind --eslint --app --yes

Then install the core package and devtools:

npm install @tanstack/react-query@5.59.0
npm install -D @tanstack/react-query-devtools@5.59.0

TanStack Query v5 removed the QueryClientProvider default cacheTime in favor of gcTime (garbage collection time). The default gcTime is 5 minutes. This change encourages more explicit cache lifetime decisions.

Create a providers file at app/providers.tsx. Because Next.js 15 App Router renders Server Components by default, we must instantiate a fresh QueryClient per request to avoid sharing mutable cache state between users.

'use client';

import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { ReactQueryDevtools } from '@tanstack/react-query-devtools';
import { useState } from 'react';

export function Providers({ children }: { children: React.ReactNode }) {
  const [queryClient] = useState(
    () => new QueryClient({
      defaultOptions: {
        queries: {
          staleTime: 30 * 1000,
          gcTime: 5 * 60 * 1000,
          retry: 2,
        },
      },
    })
  );

  return (
    <QueryClientProvider client={queryClient}>
      {children}
      <ReactQueryDevtools initialIsOpen={false} />
    </QueryClientProvider>
  );
}

Wrap your root layout with this provider. This setup isolates cache per browser session while allowing server-side prefetching to hydrate the client.

Server-Side Prefetching with QueryClient in Server Components

Next.js 15 allows direct prefetching inside Server Components or Route Handlers before rendering. Create a dedicated prefetch utility that returns both the dehydrated state and the data.

Here is a concrete implementation for fetching user analytics that will be consumed by multiple client components:

// lib/query-options.ts
import { queryOptions } from '@tanstack/react-query';

export const analyticsOptions = (userId: string) => queryOptions({
  queryKey: ['analytics', userId],
  queryFn: async () => {
    const res = await fetch(`https://api.example.com/analytics/${userId}`, {
      headers: { Authorization: `Bearer ${process.env.API_KEY}` },
    });
    if (!res.ok) throw new Error('Failed to fetch analytics');
    return res.json();
  },
  staleTime: 60 * 1000,
});

In a Server Component or a Route Handler used by generateMetadata, prefetch the data:

// app/dashboard/page.tsx
import { dehydrate, HydrationBoundary, QueryClient } from '@tanstack/react-query';
import { analyticsOptions } from '@/lib/query-options';
import DashboardClient from './DashboardClient';

export default async function DashboardPage() {
  const queryClient = new QueryClient();
  
  await queryClient.prefetchQuery(
    analyticsOptions('user_123')
  );

  return (
    <HydrationBoundary state={dehydrate(queryClient)}>
      <DashboardClient />
    </HydrationBoundary>
  );
}

This pattern eliminates the loading spinner for the initial render because the client receives fully hydrated cache data. The HydrationBoundary component from v5 serializes only the required query data, keeping payload sizes small.

Query Key Factories for Maintainable Large Codebases

Hard-coded query keys become unmanageable beyond 10 queries. TanStack Query v5 works excellently with factory functions that produce consistent keys and options.

Implement a centralized factory:

// lib/query-keys.ts
export const queryKeys = {
  users: {
    all: () => ['users'] as const,
    detail: (id: string) => ['users', id] as const,
    list: (filters: Record<string, unknown>) => ['users', 'list', filters] as const,
  },
  analytics: {
    summary: (userId: string, period: '7d' | '30d') => 
      ['analytics', userId, period] as const,
  },
  invoices: {
    all: (customerId?: string) => 
      customerId ? ['invoices', customerId] : ['invoices'],
  },
} as const;

Update the earlier query options to use these keys. This approach provides TypeScript autocomplete and prevents key collisions. When a user updates their profile, you can precisely target queryClient.invalidateQueries({ queryKey: queryKeys.users.detail(userId) }) without affecting the entire user list.

The tuple structure also enables partial matching for invalidation. Passing { queryKey: ['users'] } will invalidate every user-related query.

HydrationBoundary Deep Dive and Streaming Compatibility

Next.js 15 Partial Prerendering works together with TanStack Query when you place HydrationBoundary at the correct boundary. Data prefetched in a streaming route segment remains available to client components further down the tree.

For pages that mix static and dynamic segments, prefetch only the dynamic data inside a <Suspense> boundary. This lets static shell render immediately while dynamic data streams in.

Trade-off: Over-prefetching too many queries in a single Server Component increases TTFB. Measure with the Vercel Speed Insights or next dev --turbo and limit prefetching to data needed for the initial viewport. In practice, prefetching 2-3 critical queries usually yields the best balance.

Optimistic Updates for Responsive Interfaces

Optimistic updates remove latency perception. TanStack Query v5 provides onMutate, onError, and onSettled callbacks that integrate cleanly with Server Actions.

Consider a SaaS invoice approval button:

'use client';

import { useMutation, useQueryClient } from '@tanstack/react-query';
import { approveInvoice } from './actions';

type Invoice = { id: string; status: 'pending' | 'approved'; amount: number };

function InvoiceList({ invoices }: { invoices: Invoice[] }) {
  const queryClient = useQueryClient();

  const approveMutation = useMutation({
    mutationFn: approveInvoice,
    onMutate: async (invoiceId: string) => {
      await queryClient.cancelQueries({ 
        queryKey: queryKeys.invoices.all() 
      });
      
      const previousInvoices = queryClient.getQueryData<Invoice[]>(
        queryKeys.invoices.all()
      );

      queryClient.setQueryData(
        queryKeys.invoices.all(),
        (old: Invoice[] | undefined) =>
          old?.map((inv) =>
            inv.id === invoiceId 
              ? { ...inv, status: 'approved' as const } 
              : inv
          ) || []
      );

      return { previousInvoices };
    },
    onError: (err, variables, context) => {
      if (context?.previousInvoices) {
        queryClient.setQueryData(
          queryKeys.invoices.all(), 
          context.previousInvoices
        );
      }
    },
    onSettled: () => {
      queryClient.invalidateQueries({ 
        queryKey: queryKeys.invoices.all() 
      });
    },
  });

  return (
    <ul>
      {invoices.map((invoice) => (
        <li key={invoice.id}>
          {invoice.status === 'pending' && (
            <button
              => approveMutation.mutate(invoice.id)}
              disabled={approveMutation.isPending}
            >
              Approve
            </button>
          )}
        </li>
      ))}
    </ul>
  );
}

The optimistic update instantly reflects the new state. If the Server Action fails, the previous value is restored. This pattern improves conversion rates on action-heavy SaaS interfaces.

Infinite Queries for Feed-Style and Large Datasets

Use useInfiniteQuery when dealing with cursor-based or offset pagination. Here is a production-ready implementation using Supabase as the backend:

const {
  data,
  fetchNextPage,
  hasNextPage,
  isFetchingNextPage,
} = useInfiniteQuery({
  queryKey: queryKeys.feed.all(),
  queryFn: async ({ pageParam = 0 }) => {
    const { data, error } = await supabase
      .from('posts')
      .select('*')
      .order('created_at', { ascending: false })
      .range(pageParam, pageParam + 19);
    
    if (error) throw error;
    return data;
  },
  initialPageParam: 0,
  getNextPageParam: (lastPage, allPages) => {
    if (lastPage.length < 20) return undefined;
    return allPages.length * 20;
  },
  staleTime: 2 * 60 * 1000,
});

Combine this with IntersectionObserver via react-intersection-observer to trigger fetchNextPage() automatically. The getNextPageParam function must return undefined when no more pages exist. TanStack Query automatically flattens the pages array when you use data?.pages.flat().

Trade-off: Infinite queries increase memory usage on the client. Set a reasonable gcTime and consider clearing inactive queries when the user navigates away from the feed view using useEffect cleanup.

Cache Configuration Strategies and Concrete Recommendations

Default global options should be overridden per query based on data volatility:

  • User profile data: staleTime: 5 * 60 * 1000 (5 minutes)
  • Analytics metrics: staleTime: 30 * 1000 with refetchOnWindowFocus: false
  • Product catalog: staleTime: 3600 * 1000 (1 hour) for public data
  • Real-time collaboration state: staleTime: 0 and gcTime: 0

The gcTime controls how long inactive queries remain in cache. Setting it too low causes unnecessary refetching when users switch tabs rapidly. Setting it too high consumes memory on long-lived SPAs.

Use the QueryClient setDefaultOptions method sparingly. Most applications benefit from explicit options on each useQuery call for clarity during maintenance.

Integrating TanStack Query with Next.js Server Actions

Server Actions introduced in Next.js 13.4+ and stabilized in v15 pair naturally with mutations. Create an action that returns data and then optimistically update or invalidate:

// app/actions.ts
'use server';

import { revalidatePath } from 'next/cache';
import { queryClient } from './query-client'; // singleton for server

export async function createProject(formData: FormData) {
  const name = formData.get('name') as string;
  
  const response = await fetch('https://api.example.com/projects', {
    method: 'POST',
    body: JSON.stringify({ name }),
    headers: { 'Content-Type': 'application/json' },
  });
  
  const newProject = await response.json();
  
  // Invalidate on server so next SSR sees fresh data
  queryClient.invalidateQueries({ queryKey: ['projects'] });
  revalidatePath('/dashboard/projects');
  
  return newProject;
}

On the client, the mutation can still use onSuccess to update local UI immediately before the server revalidation completes. This dual approach gives the fastest possible UI feedback while keeping the server cache consistent.

Error Handling, Retry Logic, and Recovery Patterns

TanStack Query v5 retries failed queries twice by default with exponential backoff. Customize per domain:

useQuery({
  queryKey: ['critical-payment-data'],
  queryFn: fetchPaymentData,
  retry: (failureCount, error) => {
    if (error.message.includes('401')) return false; // auth errors
    return failureCount < 4;
  },
  retryDelay: (attempt) => Math.min(attempt * 1200, 5000),
})

For critical errors, render a custom error boundary that offers a "Retry" button calling queryClient.resetQueries(). Combine with useErrorBoundary option set to true to let React Error Boundaries catch query errors.

In production, log persistent failures to a service like Sentry inside the onError callback of a global error handler set via QueryCache.

Testing Components That Use TanStack Query

Use @tanstack/react-query test utilities with MSW for mocking network requests. Wrap tests with QueryClientProvider using a fresh client that does not retry:

const createTestQueryClient = () => new QueryClient({
  defaultOptions: {
    queries: { retry: false },
    mutations: { retry: false },
  },
});

test('renders invoice list after successful query', async () => {
  server.use(
    http.get('/api/invoices', () => 
      HttpResponse.json(mockInvoices)
    )
  );

  render(
    <QueryClientProvider client={createTestQueryClient()}>
      <InvoiceList />
    </QueryClientProvider>
  );

  expect(await screen.findByText('INV-001')).toBeInTheDocument();
});

This setup runs tests in milliseconds without real HTTP calls and prevents flakiness from network timing.

Performance Monitoring and Production Considerations

Enable React Query Devtools only in development. In production, use the useIsFetching hook to show a global "syncing" indicator for background refetches if desired.

Bundle size of @tanstack/react-query v5.59.0 is approximately 13.8 kB gzipped. Tree-shaking removes unused utilities when you import only what you need.

Decide between Server Components and TanStack Query by asking: "Does this data need real-time background updates or frequent user interactions?" Static pricing pages belong in Server Components with fetch and revalidate. Dashboards, forms with optimistic feedback, and collaborative tools benefit from client-side TanStack Query.

When using both, avoid double fetching by disabling automatic queries on the client when server data is already hydrated. The enabled: !isServerDataAvailable flag combined with a context value passed through HydrationBoundary achieves this cleanly.

Orchestrating Multiple Dependent Queries in Complex Dashboards

Real SaaS dashboards often require data from several sources: usage metrics, recent invoices, team activity, and alerts. Use useQueries (the array version) or the enabled option for dependent queries.

Example of a dependent query that only runs after the user profile is loaded:

const { data: profile } = useQuery({
  ...queryKeys.users.detail(userId),
});

const { data: usage } = useQuery({
  ...queryKeys.usage.current(profile?.plan),
  enabled: !!profile,
});

For parallel independent queries, useQueries accepts an array of query options and returns results in the same order. This reduces waterfalling and improves dashboard load times.

Apply placeholderData: keepPreviousData when switching filters or time ranges so charts do not go blank during refetching. This single option dramatically improves perceived stability of analytics interfaces.

After implementing these patterns across a 12-screen SaaS application, the architecture becomes predictable: server components deliver the initial HTML shell and critical data, TanStack Query manages subsequent interactivity and background synchronization, and Server Actions close the mutation loop. Each piece has clear responsibilities, leading to maintainable code even as the product grows from MVP to multiple enterprise customers.

The combination of Next.js 15 streaming, Partial Prerendering, and TanStack Query v5 represents the current practical frontier for building responsive, data-intensive web applications that feel instantaneous while remaining simple to reason about.

Keep reading

Related Articles