Next.jsMedium

What is React Query and how does it integrate with Next.js?

React Query, now TanStack Query, is a client-side server-state library that caches, deduplicates, refetches and mutates async data. In the App Router you add a QueryClientProvider in a Client Component, optionally prefetch on the server, and hand the cache to the client with HydrationBoundary.

Setup

  1. Create a providers.tsx Client Component that creates one QueryClient per browser session (with useState or a singleton) and renders QueryClientProvider.
  2. Wrap children with it in the root layout.
  3. Use useQuery, useSuspenseQuery, useMutation and useInfiniteQuery in Client Components.

Server prefetch + hydration

  1. In a Server Component, create a new QueryClient, run await queryClient.prefetchQuery({ queryKey, queryFn }).
  2. Render <HydrationBoundary state={dehydrate(queryClient)}> around the client component.
  3. On the client, useQuery with the same key finds the data immediately.

Set a non-zero staleTime (for example 60 seconds) so the client does not refetch right after hydration.

Streaming

TanStack Query v5 can dehydrate pending queries, so you can prefetch without awaiting and let the client suspend on the in-flight promise.

When to use it with Next.js

  • Complex client interactions: optimistic mutations, infinite lists, polling, offline support.
  • Apps migrating from a client-rendered SPA.

When not to

If data is only displayed, a Server Component is simpler. Mixing both for the same data creates two sources of truth. A common split: Server Components and Server Functions for most pages, TanStack Query for interactive widgets.

Code example

tsx
1// app/providers.tsx
2"use client";
3
4import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
5import { useState } from "react";
6
7export function Providers({ children }: { children: React.ReactNode }) {
8 const [client] = useState(() => new QueryClient({ defaultOptions: { queries: { staleTime: 60_000 } } }));
9 return <QueryClientProvider client={client}>{children}</QueryClientProvider>;
10}
11
12// app/todos/page.tsx (Server Component)
13import { dehydrate, HydrationBoundary, QueryClient } from "@tanstack/react-query";
14import { TodoList } from "./todo-list"; // "use client", useQuery({ queryKey: ["todos"], ... })
15import { getTodos } from "@/lib/todos";
16
17export default async function TodosPage() {
18 const queryClient = new QueryClient();
19 await queryClient.prefetchQuery({ queryKey: ["todos"], queryFn: getTodos });
20
21 return (
22 <HydrationBoundary state={dehydrate(queryClient)}>
23 <TodoList />
24 </HydrationBoundary>
25 );
26}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.

Open in study app