Skip to content

How to understand a TanStack Query codebase

TanStack Query manages server state: fetching, caching, refetching and updating data from APIs. Each query is identified by a key, so tracing data means following query keys from the components that use them to the mutations that invalidate them.

How to tell it's TanStack Query

  • @tanstack/react-query (or the Vue, Svelte or Solid version) in package.json
  • new QueryClient() and QueryClientProvider at the root
  • useQuery({ queryKey, queryFn }) and useMutation(...)

Where things usually live

src/lib/queryClient.ts
The client and its default options (stale time, retries).
src/queries/ or src/api/
Query functions and key factories, often with queryOptions.
src/hooks/
Custom hooks wrapping useQuery for each resource.

Conventions, not rules. Real projects rename and move things, so confirm against the repository.

Where to start reading

  1. The QueryClient setup and its defaults
  2. The query key factories
  3. Every invalidateQueries call

How a request moves through the code

  1. 1A component calls useQuery with a key and a fetch function.
  2. 2If cached data exists, it is returned immediately; if it's stale, it's refetched in the background.
  3. 3A mutation sends a write to the API.
  4. 4On success, the mutation invalidates related keys, or updates the cache directly.
  5. 5Components using those keys refetch and re-render.

Questions to ask about the repository

  • List the query keys and which endpoints they fetch.
  • Which mutations invalidate which queries?
  • What are the default stale time and retry settings?

What trips people up

  • Keys are compared by value, so a typo in a key creates a separate cache entry silently.
  • The default stale time is zero, so data refetches on window focus unless configured otherwise.