Start With One Fetch

If one component fetches one thing, fetch it in a Server Component and you're done. A query cache earns its place when several client components need the same server data, and users change it.

Take a typical case, made up for illustration. An account area fetched the order list separately in the header, the sidebar and the page, six requests per visit. Paging quickly sometimes showed page 2's orders under page 3's heading, because an older response arrived last. The wishlist heart waited for a round trip before it turned red.

TanStack Query treats server data as what it is: a cache of something that lives elsewhere. It deduplicates requests, caches by key, refetches when data goes stale, and handles mutations and optimistic updates. Below is how keys and staleness work, how to structure mutations, and where React Query fits now that Server Components handle much of the initial data.

If you fetch data in useEffect
  • You wrote useEffect + useState for every fetch and dealt with race conditions yourself
  • You triggered the same request from three components and watched it fire three times
  • After a mutation, you call refetch manually because you don't trust your invalidation
  • You're moving from v4 and aren't sure what isLoading means in v5

Queries, Keys and Staleness

TanStack Query is a cache indexed by query keys. A query key is an array; identical keys share a cache entry, share fetches (dedup), and re-render together when the entry updates.


flowchart LR
    A["useQuery(['posts', id])"] --> B{"Cache hit?"}
    B -->|Fresh| C["Return cached data"]
    B -->|Stale| D["Return cached + refetch in bg"]
    B -->|Miss| E["Fetch, then cache"]
    F["useMutation(updatePost)"] --> G["Run mutationFn"]
    G --> H["onSuccess: invalidateQueries(['posts'])"]
    H --> I["Marks matching keys stale"]
    I --> D

    style B fill:#4f46e5,color:#fff,stroke:#4338ca
    style H fill:#059669,color:#fff,stroke:#047857

Two timer concepts trip everyone up:

  • staleTime — how long data is considered fresh. While fresh, no automatic refetch on mount/focus/reconnect. Default: 0 (always stale).
  • gcTime (was cacheTime) — how long an inactive entry survives in cache before garbage collection. Default: 5 minutes.
✅

Check it: Open the network tab and load one page. Count the requests for the same resource. With a shared key, there should be one.

Queries and Mutations in Practice

Step 1: Set up the provider once

// app/providers.tsx
'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 }) {
  // useState keeps one client per mounted provider, so re-renders don't reset the cache
  const [client] = useState(() => new QueryClient({
    defaultOptions: {
      queries: {
        staleTime: 60_000,          // treat data fresh for 60s
        gcTime: 5 * 60_000,         // garbage-collect after 5min inactive
        refetchOnWindowFocus: true, // bring data back when tab regains focus
        retry: 2,
      },
    },
  }));
  return (
    <QueryClientProvider client={client}>
      {children}
      <ReactQueryDevtools initialIsOpen={false} />
    </QueryClientProvider>
  );
}

Step 2: Queries — keep keys hierarchical and serializable

'use client';
import { useQuery } from '@tanstack/react-query';

async function fetchPost(id: string): Promise<Post> {
  const res = await fetch(`/api/posts/${id}`);
  if (!res.ok) throw new Error('Failed');
  return res.json();
}

export function PostView({ id }: { id: string }) {
  const { data, isPending, error } = useQuery({
    queryKey: ['posts', id],     // hierarchical: ['posts'] → ['posts', id]
    queryFn: () => fetchPost(id),
    enabled: !!id,                // skip until id is truthy
  });

  if (isPending) return <Skeleton />;
  if (error) return <ErrorCard error={error} />;
  return <Article post={data} />;
}

Hierarchical keys let you invalidate by prefix: queryClient.invalidateQueries({ queryKey: ['posts'] }) nukes every post.

Step 3: useSuspenseQuery + Suspense (React 19)

'use client';
import { useSuspenseQuery } from '@tanstack/react-query';
import { Suspense } from 'react';

function PostInner({ id }: { id: string }) {
  // No isPending/isError — Suspense boundary handles loading,
  // ErrorBoundary handles errors. data is non-nullable.
  const { data } = useSuspenseQuery({
    queryKey: ['posts', id],
    queryFn: () => fetchPost(id),
  });
  return <Article post={data} />;
}

export function PostView({ id }: { id: string }) {
  return (
    <Suspense fallback={<Skeleton />}>
      <PostInner id={id} />
    </Suspense>
  );
}

Step 4: Mutations with invalidation

'use client';
import { useMutation, useQueryClient } from '@tanstack/react-query';

export function usePublishPost() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: async (id: string) => {
      const r = await fetch(`/api/posts/${id}/publish`, { method: 'POST' });
      // fetch only rejects on network failure, so throw for 4xx/5xx or onError never runs
      if (!r.ok) throw new Error(`Publish failed: ${r.status}`);
      return r.json();
    },
    onSuccess: (_data, id) => {
      // Mark every matching query stale → background refetch
      qc.invalidateQueries({ queryKey: ['posts', id] });
      qc.invalidateQueries({ queryKey: ['posts', 'list'] });
    },
  });
}
✅

Check it: Change something and watch the lists that show it. They should refresh with no manual refetch in your code.

Step 5: Optimistic updates

const qc = useQueryClient();
const mutation = useMutation({
  mutationFn: (newTitle: string) => updateTitle(id, newTitle),
  onMutate: async (newTitle) => {
    // 1) Cancel any in-flight refetches for this key
    await qc.cancelQueries({ queryKey: ['posts', id] });
    // 2) Snapshot for rollback
    const previous = qc.getQueryData<Post>(['posts', id]);
    // 3) Optimistically write the new value
    qc.setQueryData<Post>(['posts', id], (old) =>
      old ? { ...old, title: newTitle } : old,
    );
    return { previous };
  },
  onError: (_err, _vars, ctx) => {
    // 4) Rollback on failure
    if (ctx?.previous) qc.setQueryData(['posts', id], ctx.previous);
  },
  onSettled: () => {
    // 5) Refetch to sync with server truth
    qc.invalidateQueries({ queryKey: ['posts', id] });
  },
});
✅

Check it: Throttle the network, toggle something twice quickly, and make one request fail. The screen should end in the true state.

Step 6: Hydrate from a Server Component (Next.js 16)

// app/posts/[id]/page.tsx — Server Component prefetches, Client renders
import { dehydrate, HydrationBoundary, QueryClient } from '@tanstack/react-query';
import { PostView } from './post-view';

export default async function Page({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const qc = new QueryClient();
  await qc.prefetchQuery({
    queryKey: ['posts', id],
    queryFn: () => fetchPostFromDb(id),
  });
  return (
    <HydrationBoundary state={dehydrate(qc)}>
      <PostView id={id} />
    </HydrationBoundary>
  );
}

Paging Without Wrong Pages or Flicker

The account area from the introduction showed page 2’s orders under page 3’s heading because two responses raced and the older one landed last. With React Query that bug cannot happen by construction: each page has its own cache entry, keyed by page, so a late response for page 2 writes to page 2’s entry and never to the one you are looking at. The remaining problem is the flash of a loading state on every page change, which is what keepPreviousData is for:

import { keepPreviousData, queryOptions, useQuery, useQueryClient } from '@tanstack/react-query';
import { useEffect } from 'react';

const ordersPage = (page: number) =>
  queryOptions({
    queryKey: ['orders', 'list', { page }],
    queryFn: () => fetchOrders(page),
    staleTime: 30_000,
  });

function OrderList({ page }: { page: number }) {
  const queryClient = useQueryClient();
  const { data, isPlaceholderData } = useQuery({
    ...ordersPage(page),
    placeholderData: keepPreviousData,   // keep showing the last page while the next one loads
  });

  useEffect(() => {
    if (!isPlaceholderData && data?.hasMore) {
      void queryClient.prefetchQuery(ordersPage(page + 1));   // the next click is instant
    }
  }, [data, isPlaceholderData, page, queryClient]);

  // render data.items; dim the list and disable "Next" while isPlaceholderData is true
}

isPlaceholderData tells you the list on screen belongs to the previous page, so you can dim it and disable the next-page button until real data arrives. Without that, users click “Next” twice on a slow connection and skip a page.

✅

Check it: Page forward quickly on a slow connection. The heading and the rows should always belong to the same page.

One Definition per Query

The snippet above also shows the habit that keeps a growing app manageable: define each query once with queryOptions and reuse that definition everywhere. The same object feeds useQuery, prefetchQuery in a route loader,getQueryData for optimistic updates and server-side hydration, with the key and the data type staying in sync. When keys are written by hand in several files, sooner or later one of them is ['orders', page] and another is['orders', 'list', { page }], invalidation stops reaching half the screens, and the header shows a stale count that nobody can explain.

Testing Components That Fetch

Tests that share one QueryClient leak cached data between cases, and the default retries make failing requests take seconds to fail. Create a fresh client per test with retries turned off, wrap the component in its provider, and mock the network at the HTTP layer (for example with Mock Service Worker) rather than mocking React Query itself. Then the test exercises the real caching and loading states your users see, and a test for the error state finishes immediately instead of waiting out three retries.

How React Query Setups Go Wrong

1. Forgetting useState(() => new QueryClient()). Constructing the client at module scope shares cache across users on the server (SSR) and constructing it inside the component without useState creates a new client every render. Both are bugs.

2. Object as query key. Keys are compared by deep equality but are easier to reason about as primitive arrays. Prefer['posts', id, { sort: 'date' }] over deeply nested objects.

3. staleTime: 0 + refetchOnWindowFocus: true. Defaults that look helpful but cause refetch storms when users tab back. Set a sane staleTime per query type.

4. Using React Query for one-shot data the server already has. If a Server Component can fetch it directly and pass it as a prop, do that. React Query shines for client-driven, repeatedly-fetched, mutation-coupled data.

5. Forgetting to cancelQueries in optimistic onMutate. An in-flight refetch can land after your optimistic update and overwrite it. Always cancel first.

6. v5 mental model gaps. The old "no data yet" meaning of isLoading is now isPending. isLoading still exists, but it now means isPending && isFetching: no data and a request in flight, so it stays false on a disabled query. isFetching is any in-flight request including background refetch. cacheTime renamed to gcTime. Update your code, not just your tsconfig.

How I Use It Today

  • One QueryClient per browser session, created via useState(() => new QueryClient()).
  • Hierarchical query keys + prefix invalidation is the cleanest cache shape.
  • Set staleTime per resource — 0 is rarely right.
  • Use useSuspenseQuery + <Suspense> + ErrorBoundary in React 19 — eliminates branching on isPending/error at every call site.
  • Optimistic updates: cancel → snapshot → write → rollback on error → refetch on settled.
  • Prefetch in a Server Component and hydrate via HydrationBoundary for instant-loading Client widgets.
  • Install ReactQueryDevtools — most query bugs are obvious in the panel.

Try It on Your Own System This Week

Three checks on an app that uses a query cache, about an hour in total:

  1. Find where the query client is created. At module scope on the server, it shares its cache between users.
  2. Search for the same query written out in more than one place. Define each one once, and reuse the definition.
  3. Open the devtools panel on a busy page. Most query bugs are plain to see there.

Keeping Up With Server Components

TanStack Query works alongside Server Components: prefetch on the server, dehydrate the cache, and hydrate in a client boundary. Use it for client-driven data such as infinite lists and polling, and let Server Components fetch what doesn't need client interaction.