Master TanStack Query for React Apps
Production TanStack Query patterns for React/Next.js: query key factories, mutations, optimistic updates, and SSR hydration.
Why it matters
Leverage TanStack Query to build robust, performant asynchronous state management layers in React and Next.js applications, optimizing data fetching and caching.
Outcomes
What it gets done
Implement declarative data fetching and caching strategies.
Configure query keys, staleTime, and gcTime for optimal performance.
Handle mutations, cache invalidation, and optimistic UI updates.
Integrate with Next.js App Router for server-side rendering and hydration.
Install
Add it to your toolbox
Run in your project directory:
curl -fsSL https://spark.entire.vc/get/ag-tanstack-query-expert | bash Overview
TanStack Query Expert
A TanStack Query skill for React/Next.js covering typed query hooks, mutations with cache invalidation, optimistic updates, and App Router SSR hydration. Use when replacing useEffect-based data fetching, designing query keys, writing mutations, or integrating TanStack Query with Next.js Server Components.
What it does
Guides production-grade TanStack Query (React Query) usage in React and Next.js apps: declarative data fetching, cache invalidation, optimistic UI updates, background syncing, and SSR hydration. Its core rule is never using useEffect to fetch data when TanStack Query is available, since it is an asynchronous state manager handling caching, deduplication, pagination, and loading/error states out of the box. It documents the custom-hook pattern for abstracting useQuery calls behind typed hooks with array-based query keys, a query-key factory pattern for large apps that avoids key-spelling mismatches like ['users'] versus ['user'], a useMutation plus queryClient.invalidateQueries pattern for cache invalidation after writes, and a full optimistic-update pattern where onMutate cancels in-flight refetches and snapshots then overwrites the cache, onError rolls back from the snapshot, and onSettled invalidates to resync with the server. For Next.js App Router it covers initializing a QueryClientProvider with sane defaults (staleTime, refetchOnWindowFocus: false) and server-component prefetching via queryClient.prefetchQuery plus dehydrate/HydrationBoundary, so the client component reads instantly from the dehydrated cache instead of triggering a network request on mount. Best practices cover setting a non-zero global staleTime since the default of 0 triggers a background refetch on every remount, preferring invalidateQueries over manual setQueryData, and never syncing query data into local React state with a useEffect. It also documents two specific troubleshooting cases: an infinite fetch loop traced to an unhandled queryFn exception triggering TanStack Query's default three retries, and the distinction between staleTime (when a background refetch triggers) and gcTime (how long inactive data survives after unmount), warning that a gcTime shorter than staleTime deletes data before it even goes stale.
When to use - and when NOT to
Use it when setting up or refactoring data-fetching logic to replace useEffect/useState, designing array-based typed query keys, configuring staleTime, gcTime, or retry behavior, writing useMutation hooks for POST/PUT/DELETE, invalidating the cache after a mutation, implementing optimistic updates, or integrating TanStack Query with Next.js App Router Server Components and client-boundary hydration.
Inputs and outputs
Input is a data-fetching or mutation requirement in a React or Next.js app. Output is TypeScript hooks and provider setup following the documented patterns, for example a query-key factory:
export const issueKeys = {
all: ['issues'] as const,
lists: () => [...issueKeys.all, 'list'] as const,
list: (filters: string) => [...issueKeys.lists(), { filters }] as const,
details: () => [...issueKeys.all, 'detail'] as const,
detail: (id: number) => [...issueKeys.details(), id] as const,
};
Integrations
Built on @tanstack/react-query (useQuery, useMutation, useQueryClient) and its Next.js App Router hydration APIs (QueryClient, dehydrate, HydrationBoundary).
Who it's for
React and Next.js developers replacing ad hoc useEffect data fetching with a proper async state layer, including SSR-hydrated Server Component data flows.
FAQ
Common questions
Discussion
Questions & comments ยท 0
Sign In Sign in to leave a comment.