v3
Back to blog
·6 min read·MAD Software

TanStack Query Patterns for Next.js

Server state management done right. Caching, deduplication, background refetching, and optimistic updates.

React
Data Fetching
TanStack Query

TanStack Query (formerly React Query) is the standard for managing server state in React applications. It handles caching, background refetching, stale-while-revalidate, and much more.

Setup

Wrap your app with `QueryProvider` (already done in this starter kit's root layout).

Basic Query

function UserProfile({ userId }: { userId: string }) { const { data, isLoading, error } = useQuery({ queryKey: ["user", userId], queryFn: () => fetch(`/api/users/${userId}`).then(r => r.json()), });

if (isLoading) return <Skeleton />; if (error) return <ErrorFallback error={error} />; return <ProfileCard user={data} />; } ```

Mutations

const mutation = useMutation({
  mutationFn: (data: ProfileValues) => fetch("/api/profile", {
    method: "PATCH",
    body: JSON.stringify(data),
  }),
  onSuccess: () => {
    queryClient.invalidateQueries({ queryKey: ["user"] });
    toast.success("Profile updated!");
  },
});

The key insight: queries are for reading, mutations are for writing. TanStack Query handles the cache invalidation between them.