TanStack Query

Knowledge base from the official TanStack Query (React Query) v5 documentation — server-state fetching, caching, and mutation library for React. Use when building or debugging data fetching with useQuery/useMutation/useInfiniteQuery, caching/invalidation strategy, optimistic updates, SSR/hydration with Next.js or Remix, Suspense integration, or migrating from React Query v3/v4.

80 capítulos

TanStack Query

Package: @tanstack/react-query | Chapters: 80 (34 Guides + 8 Overview + 3 Migrations + ESLint + 5 Persisters + 10 Core API + 19 React API) | Generated: 2026-08-25

How to Use This Skill

  • Without arguments — load Core Patterns below for the read/write/invalidate mental model shared across the whole library
  • With a concept name — ask about optimistic updates, infinite queries, SSR, useMutation, etc.; I find and read the matching chapter
  • With a chapter — ask for ch030; I load that specific chapter
  • Browse — ask "what chapters do you have?" to see the full index

When you ask about a topic not covered in Core Patterns below, I will read the relevant chapter file before answering.


Core Patterns & Conventions

Server state, not client state. This library exists for data owned by a server that can go stale — not a replacement for useState/Redux/Zustand for purely local UI state.

The read → write → invalidate loop is the whole mental model. useQuery reads a cache entry keyed by queryKey; useMutation performs a write; queryClient.invalidateQueries({ queryKey }) from the mutation's onSuccess tells stale reads to refresh. Nearly every advanced feature (optimistic updates, infinite queries, prefetching) is a variation on this loop.

Query keys are the dependency array of the fetcher. Every value a queryFn closes over that can change must be in queryKey, or the cache can't tell requests apart. The exhaustive-deps ESLint rule enforces this automatically.

status answers "do we have data?"; fetchStatus answers "is the fetcher running?" They combine independently — a query can be pending and paused (offline, first mount) at once. Use isLoading (not isPending) for "show a spinner because this is genuinely fetching right now."

Defaults are aggressive on purpose. staleTime: 0 (stale immediately), gcTime 5 minutes, retry: 3 with backoff for queries but retry: 0 for mutations — know these before debugging "why does it refetch so much."

Every dependent query is a request waterfall. Prefer flattening the backend API (a combined endpoint) over accepting a chained enabled: !!x fetch when performance matters.

Suspense queries side by side in one component serialize, not parallelize. Reach for useSuspenseQueries/useSuspenseInfiniteQuery combinations the moment more than one lives together.

SSR needs a per-request QueryClient, never a module-scoped one. Prefetch in a loader → dehydrate()<HydrationBoundary> on the client, with a non-zero staleTime to avoid an immediate refetch.

Install @tanstack/eslint-plugin-query's flat/recommended from day one. It automates enforcement of most of the gotchas above (exhaustive-deps, stable-query-client, no-rest-destructuring, no-void-query-fn, and more).


Chapter Index

Overview / Get Started

#TitleKey Concepts
ch001Overviewserver state vs. client state, core primitives
ch002Installationnpm/CDN install, ESLint plugin
ch003Quick Startread → write → invalidate loop
ch004DevtoolsFloating/Embedded mode, production lazy-load
ch005Comparisonvs. SWR, Apollo, RTK Query
ch006TypeScriptinference, Register, queryOptions
ch007GraphQLqueryFn as any Promise-returning client
ch008React NativeonlineManager, focusManager, AppState

Guides

#TitleKey Concepts
ch009Important DefaultsstaleTime, gcTime, retry, structural sharing
ch010Queriesstatus, fetchStatus
ch011Query Keysdependency rule, hashing
ch012Query FunctionsQueryFunctionContext, error contract
ch013Query OptionsqueryOptions helper
ch014Network Modeonline/always/offlineFirst
ch015Parallel Queriesmanual vs. useQueries
ch016Dependent Queriesenabled, waterfalls
ch017Background Fetching IndicatorsisFetching, useIsFetching
ch018Window Focus RefetchingfocusManager
ch019PollingrefetchInterval
ch020Disabling/Pausing Queriesenabled, skipToken, lazy queries
ch021Query Retriesretry, retryDelay, failureReason
ch022Paginated / Lagged QuerieskeepPreviousData
ch023Infinite QueriesfetchNextPage, maxPages
ch024Initial Query DatainitialData, initialDataUpdatedAt
ch025Placeholder Query DataplaceholderData, isPlaceholderData
ch026Mutationsmutate/mutateAsync, callbacks, scope
ch027Query InvalidationinvalidateQueries matching
ch028Invalidations from MutationsonSuccess pattern
ch029Updates from Mutation ResponsessetQueryData, immutability
ch030Optimistic Updatesvia UI vs. via cache, rollback
ch031Query CancellationAbortSignal, cancelQueries
ch032Scroll Restorationcache stability
ch033FiltersQueryFilters, MutationFilters
ch034Performance & Request Waterfallsserial vs. parallel
ch035Prefetching & Router IntegrationqueryClient.query(), router loaders
ch036Server Rendering & Hydrationdehydrate/HydrationBoundary
ch037Advanced Server RenderingServer Components, streaming
ch038Caching Examplesfull cache lifecycle walkthrough
ch039Render Optimizationstracked properties, select
ch040Default Query Functionkey-only queries
ch041SuspenseuseSuspenseQuery, error boundaries
ch042TestingrenderHook, mocking network calls

Migrations

#TitleKey Concepts
ch043Migrating to React Query 3QueryClient split
ch044Migrating to React Query 4@tanstack scope, array keys
ch045Migrating to TanStack Query v5gcTime, isPending, object signature

ESLint Plugin

#TitleKey Concepts
ch046ESLint Plugin Queryall 8 rules, flat/recommended

Plugins (Persisters)

#TitleKey Concepts
ch047persistQueryClientdehydrate/hydrate, gcTime/maxAge
ch048createSyncStoragePersisterdeprecated, localStorage
ch049createAsyncStoragePersisterrecommended, AsyncStorage
ch050broadcastQueryClient (Experimental)cross-tab sync
ch051experimental_createQueryPersisterper-query persistence

Core API

#TitleKey Concepts
ch052QueryClientbulk operations, defaults
ch053QueryCacheglobal callbacks, find/findAll
ch054MutationCacheglobal callbacks
ch055QueryObserver, InfiniteQueryObserver & QueriesObserverframework-agnostic layer
ch056streamedQuery (Experimental)AsyncIterable, chat UIs
ch057FocusManagersetEventListener, setFocused
ch058OnlineManagerconnectivity detection
ch059environmentManagerserver/client detection
ch060NotifyManagerbatching, scheduling
ch061TimeoutManagercustom timer providers

React API

#TitleKey Concepts
ch062useQueryfull option/return reference
ch063useQueriescombine option
ch064useInfiniteQueryfull option/return reference
ch065useMutationfull option/return reference
ch066useIsFetchingapp-wide loading indicator
ch067useIsMutatingapp-wide loading indicator
ch068useMutationStatecross-component mutation access
ch069useSuspenseQueryguaranteed-defined data
ch070useSuspenseInfiniteQuerySuspense + infinite
ch071useSuspenseQueriesparallel Suspense fix
ch072QueryClientProvidercontext setup
ch073useQueryClientimperative client access
ch074queryOptionstype-preserving helper
ch075infiniteQueryOptionstype-preserving helper
ch076mutationOptionstype-preserving helper
ch077usePrefetchQuerySuspense-safe prefetch
ch078usePrefetchInfiniteQuerySuspense-safe prefetch
ch079QueryErrorResetBoundary & useQueryErrorResetBoundaryresettable error boundaries
ch080Hydration API — dehydrate, hydrate, HydrationBoundarylow-level SSR primitives

Topic Index

  • Caching lifecycle (staleTime/gcTime) → ch009, ch038, ch062
  • Devtools → ch004
  • ESLint rules → ch046
  • Infinite queries → ch023, ch064, ch070, ch075, ch078
  • Migration (v3→v4→v5) → ch043, ch044, ch045
  • Mutations → ch026, ch028, ch029, ch065, ch068, ch076
  • Network/offline handling → ch008, ch014, ch044, ch058
  • Optimistic updates → ch030, ch068
  • Performance / waterfalls → ch034, ch035, ch039
  • Persistence (storage/cross-tab) → ch047–ch051
  • Query keys → ch011, ch046
  • Render optimizations (select, tracked properties) → ch013, ch039, ch046
  • Server rendering / hydration → ch036, ch037, ch080
  • Suspense → ch041, ch069–ch071, ch077, ch078, ch079
  • Testing → ch042
  • TypeScript → ch006, ch013, ch063

Supporting Files

Scope & Limits

This skill covers the official TanStack Query v5 documentation (React adapter, @tanstack/react-query) as of the fetch date in the source — the framework-agnostic core (@tanstack/query-core) is covered only through the React-facing surface documented here. Other framework adapters (Vue, Solid, Svelte, Angular) are not covered.

The historical v3/v4 migration chapters (ch043, ch044) are condensed — they summarize the major renames and breaking changes rather than reproducing every codemod command and code diff, since most projects on this skill's stack (Next.js/React) are already on v5 or migrating directly to it.

tanstack-query-examples.txt (60 aggregated example READMEs/entry points from the TanStack Query GitHub repo) was used to sanity-check and enrich the Mutations/Optimistic Updates guidance above, not turned into its own chapters — it was mostly minimal per-example boilerplate without much unique conceptual content beyond what the main docs already cover.

Related skills: react-hook-form-docs — a common integration pairing (forms + server-state cache). react-docs, if present in this library, covers the underlying React hooks/rendering model this library builds on.