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) inpackage.jsonnew QueryClient()andQueryClientProviderat the rootuseQuery({ queryKey, queryFn })anduseMutation(...)
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
useQueryfor each resource.
Conventions, not rules. Real projects rename and move things, so confirm against the repository.
Where to start reading
- The
QueryClientsetup and its defaults - The query key factories
- Every
invalidateQueriescall
How a request moves through the code
- A component calls
useQuerywith a key and a fetch function. - If cached data exists, it is returned immediately; if it's stale, it's refetched in the background.
- A mutation sends a write to the API.
- On success, the mutation invalidates related keys, or updates the cache directly.
- Components 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.