TanStack Query: the life of useQuery
Overview
Follow one useQuery call through QueryClient, QueryCache, Query and QueryObserver: how a key becomes a cached query, when data is stale, why two components fetch once and when the cache forgets.
TanStack Query's React package is thin: almost everything useQuery does happens in @tanstack/query-core, a library that knows nothing about React. This tour follows one useQuery({ queryKey, queryFn }) call at the @tanstack/react-query@5.107.1 tag: from the hook through the options and the query hash into the QueryCache, to the Query that fetches and the QueryObserver that turns its state into what your component renders. Then the data's later life: staleness, refetching on focus, structural sharing, render tracking and garbage collection.
Mutations, infinite queries, suspense and error boundaries, SSR hydration, the retryer's internals and notifyManager batching are left out.
How the pieces connect
Select a box to open the step that explains it. Dashed boxes are mentioned but not covered.
- useQuery → useBaseQuery (calls)
- useBaseQuery → defaultQueryOptions (calls)
- defaultQueryOptions → hashKey (hashes)
- useBaseQuery → QueryObserver (creates)
- useBaseQuery → useSyncExternalStore (subscribes)
- QueryObserver → QueryCache.build (get or create)
- QueryObserver → Query.fetch (fetches if stale)
- Query.fetch → replaceEqualDeep (new data)
- Query.fetch → updateResult (notifies)
- updateResult → useSyncExternalStore (re-render)