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
- Create a
providers.tsxClient Component that creates oneQueryClientper browser session (withuseStateor a singleton) and rendersQueryClientProvider. - Wrap
childrenwith it in the root layout. - Use
useQuery,useSuspenseQuery,useMutationanduseInfiniteQueryin Client Components.
Server prefetch + hydration
- In a Server Component, create a new
QueryClient, runawait queryClient.prefetchQuery({ queryKey, queryFn }). - Render
<HydrationBoundary state={dehydrate(queryClient)}>around the client component. - On the client,
useQuerywith 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
1// app/providers.tsx2"use client";34import { QueryClient, QueryClientProvider } from "@tanstack/react-query";5import { useState } from "react";67export 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}1112// 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";1617export default async function TodosPage() {18 const queryClient = new QueryClient();19 await queryClient.prefetchQuery({ queryKey: ["todos"], queryFn: getTodos });2021 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.