Capítulo 55 de 80

Chapter 55: QueryObserver, InfiniteQueryObserver & QueriesObserver

Core Idea

These are the framework-agnostic classes useQuery/useInfiniteQuery/useQueries are thin wrappers around — construct one directly (rare) to observe query state outside of React entirely, e.g. in a vanilla-JS integration or a custom framework binding.

Key Concepts

  • QueryObserver: new QueryObserver(queryClient, options) where options is exactly useQuery's option shape — .subscribe(callback) fires with each result, returns an unsubscribe function.
  • InfiniteQueryObserver: same pattern, options shape matches useInfiniteQuery (queryFn, getNextPageParam/getPreviousPageParam, etc.).
  • QueriesObserver: takes an array of query option objects (matching useQueries' shape) instead of one — observes multiple queries as a single subscription.
  • Why this exists: useQuery/useInfiniteQuery/useQueries are React bindings around these observer classes — this is the layer other framework adapters (Vue, Solid, Svelte, Angular) build their own reactive bindings on top of, and the layer you'd reach for to observe queries somewhere with no React component tree at all (e.g. a non-React state manager, a vanilla script).

Code Examples

const observer = new QueryObserver(queryClient, { queryKey: ['posts'], queryFn: fetchPosts })
const unsubscribe = observer.subscribe((result) => {
  console.log(result)
})
  • What it demonstrates: subscribing to a query's live result outside any React hook.

Key Takeaways

  1. Reach for these classes only when integrating TanStack Query outside a React component tree — inside React, useQuery/useInfiniteQuery/useQueries are always the right layer.
  2. Their option shapes are identical to the corresponding hook's — nothing new to learn beyond "same options, manual subscribe/unsubscribe."

Connects To

  • Queries / Infinite Queries / Parallel Queries: the hook-level equivalents these classes power internally.