QueryClient Reference
Purpose and Scope
QueryClient is the imperative interface for working with TanStack Query's cache. Application code most often reads server state through framework-native APIs such as React hooks or Angular injection functions, but those APIs all need a client behind them. The client owns the query cache, mutation cache, default options, and the operations that fetch, prefetch, invalidate, refetch, cancel, reset, remove, or inspect cached work. This page is a reference-oriented guide to that public surface, with special attention to how the Angular adapter documentation wires a QueryClient into an application.
Sources: docs/framework/angular/reference/functions/provideTanStackQuery.md, docs/framework/angular/angular-httpclient-and-other-data-fetching-clients.md
The Angular reference demonstrates the adapter-level contract clearly: provideTanStackQuery(queryClient, ...features): Provider[] accepts either a QueryClient instance or an Angular InjectionToken<QueryClient> and returns Angular providers that enable TanStack Query functionality. That means the QueryClient is not a React-only concept. It is the shared cache coordinator that framework packages expose through framework-specific integration points. In Angular, providers connect the client to injectQuery, injectIsFetching, devtools features, and any optional features passed through provideTanStackQuery.
Sources: docs/framework/angular/reference/functions/provideTanStackQuery.md, docs/framework/angular/devtools.md
Use this page when you need to decide whether to call a client method directly instead of relying only on query or mutation observers. Direct calls are appropriate for route preloading, warming data before navigation, invalidating affected resources after a write, reading cached data for optimistic UI, or configuring defaults at application startup. The public client API is intentionally broad, so the most important distinction is between methods that execute network work, methods that read or write cache state synchronously, and methods that change cache policy or lifecycle behavior.
Relevant Source Files
docs/framework/angular/reference/functions/provideTanStackQuery.md- Documents the Angular provider function that accepts aQueryClient, supports optional features such as devtools, and shows standalone, NgModule, andInjectionTokensetup forms.docs/framework/angular/angular-httpclient-and-other-data-fetching-clients.md- Explains that TanStack Query fetching is promise-based and client-agnostic, including AngularHttpClientusage through promise conversion inqueryFn.docs/framework/angular/devtools.md- ShowsQueryClientbeing supplied toprovideTanStackQuerywithwithDevtools, including development-only behavior and production loading options.docs/framework/angular/guides/background-fetching-indicators.md- Shows adapter-level fetching state throughinjectQueryandinjectIsFetching, which corresponds to the client-level ability to count active fetches.docs/config.json- Places Angular, React, Vue, Solid, Svelte, Lit, and other framework documentation in the official docs navigation, confirming this reference sits in a multi-framework documentation structure.docs/community-resources.md- Lists ecosystem utilities such as query key factories, OpenAPI client generation, GraphQL code generation, and normalization helpers that commonly shape how teams useQueryClientcache APIs.
Creating and Providing a QueryClient
A typical application creates one long-lived QueryClient for a runtime boundary and provides it near the root of the app. In Angular, the documented standalone setup imports provideTanStackQuery and QueryClient from @tanstack/angular-query-experimental, then passes provideTanStackQuery(new QueryClient()) into bootstrapApplication. The NgModule setup follows the same pattern in the module providers array. Both examples communicate the same design: create the client once, provide it through the framework, and let query functions, observers, and utilities share that cache.
Sources: docs/framework/angular/reference/functions/provideTanStackQuery.md
The Angular provider reference also supports an advanced InjectionToken form. Instead of passing a constructed client directly, an application can define an injection token whose factory returns new QueryClient() and then pass that token to provideTanStackQuery. The documentation frames this as a lazy-loading optimization that can keep TanStack Query out of the main application bundle while still sharing a client on lazy loaded routes. For most applications, however, the same page recommends providing the QueryClient in the main application config because the simpler root-level setup is easier to reason about.
Sources: docs/framework/angular/reference/functions/provideTanStackQuery.md
Optional features are layered on top of the same client provider. The devtools docs show provideTanStackQuery(new QueryClient(), withDevtools()), while the provider reference states that features are optional QueryFeatures used to configure additional Query functionality. This is an important mental model for the public surface: the client remains the cache and execution coordinator, while feature helpers integrate extra behavior around it. Devtools, for example, inspect queries and mutations that belong to the provided client instead of creating an independent data store.
Sources: docs/framework/angular/reference/functions/provideTanStackQuery.md, docs/framework/angular/devtools.md
Public API Surface
The official QueryClient reference groups the public methods into several practical families. Fetching methods execute query functions and return data or promises for completion. Cache read and write methods inspect or update data without necessarily mounting a framework observer. Invalidation and refetch methods mark matching queries stale or actively re-run them. Mutation and activity methods expose counts and mutation lifecycle controls. Defaults and cache accessors configure behavior for future work or expose the underlying query and mutation caches when lower-level coordination is needed.
Sources: docs/framework/angular/guides/background-fetching-indicators.md
| Category | Public methods | Typical use |
|---|---|---|
| Fetch and prefetch | fetchQuery, fetchInfiniteQuery, prefetchQuery, prefetchInfiniteQuery, ensureQueryData, ensureInfiniteQueryData | Load data before rendering, route transitions, or user interaction. |
| Cache reads | getQueryData, getQueriesData, getQueryState | Inspect data, timestamps, status, or sets of matching queries. |
| Cache writes | setQueryData, setQueriesData | Seed data, update optimistic results, or apply server responses. |
| Query lifecycle | invalidateQueries, refetchQueries, cancelQueries, removeQueries, resetQueries | Coordinate freshness, background work, cancellation, and cache cleanup. |
| Activity state | isFetching, isMutating | Drive global indicators and debugging views. |
| Defaults | getDefaultOptions, setDefaultOptions, getQueryDefaults, setQueryDefaults, getMutationDefaults, setMutationDefaults | Configure app-wide and key-scoped behavior. |
| Caches and mutations | getQueryCache, getMutationCache, resumePausedMutations, clear | Integrate persistence, offline mutation recovery, devtools, or full cache teardown. |
The fetch and prefetch methods are the imperative equivalents of declaring a query through an adapter. A fetch method is useful when the caller needs the data result immediately and wants errors to be surfaced to the calling code. A prefetch method is useful when the application wants to warm the cache but does not need to use the returned data at that call site. The Angular data-fetching guide reinforces that query execution is promise-oriented and backend-agnostic: a queryFn can use browser fetch, graphql-request, Angular HttpClient, or another async client as long as it resolves through a promise.
Sources: docs/framework/angular/angular-httpclient-and-other-data-fetching-clients.md
Cache read and write methods are where QueryClient becomes more than a request runner. getQueryData and getQueriesData let application code consult the cache by query key or filter. setQueryData and setQueriesData let code update cached records after a mutation or seed known data before a view mounts. These methods should be used with deliberate query key design because the key is the identity of the cached resource. The community resources page calls out utilities such as Query Key Factory, GraphQL Code Generator, Orval, and React Query Kit, all of which reflect common ecosystem patterns for standardizing keys and generated query usage.
Sources: docs/community-resources.md
Invalidation, refetching, cancellation, reset, and removal methods are lifecycle controls. Invalidation marks matching queries as out of date so observers can pick up fresh data according to their options. Refetching actively asks matching queries to run again. Cancellation is important when an in-flight result should no longer update the cache, such as a user leaving a screen or an optimistic mutation needing to prevent stale overwrites. Reset and removal are stronger operations: reset returns queries to their initial state, while removal deletes cached entries that should no longer be retained.
Activity, Devtools, and Fetching Indicators
The client's activity methods connect directly to user experience. isFetching returns the number of matching queries currently fetching, while isMutating does the same for mutations. Angular's guide presents the framework-facing version through injectIsFetching, rendering a global loading indicator when any query is fetching in the background. It also shows a per-query distinction between pending initial load and background refresh: isPending() renders initial loading, while isFetching() inside a successful query can display Refreshing... without replacing already available data.
Sources: docs/framework/angular/guides/background-fetching-indicators.md
Devtools are another consumer of the same client-owned state. The Angular devtools guide says the tools help debug and inspect queries and mutations, then enables them by adding withDevtools to provideTanStackQuery. By default, Angular Query Devtools are included only in development mode bundles. Production usage is possible through the @tanstack/angular-query-experimental/devtools/production subpath and the loadDevtools option, which can be set to auto, true, or false through a callback that supports Angular reactivity.
Sources: docs/framework/angular/devtools.md
These debugging and indicator APIs are valuable because server state often changes outside the current component. A screen can have usable cached data while a background refetch is in progress, or a mutation can be pending in a different part of the application. Rather than manually wiring loading flags across components, the client exposes aggregate state from its caches. Framework adapters then project that state into hooks, composables, signals, or injected functions so UI code can stay idiomatic without losing access to cache-wide activity.
Sources: docs/framework/angular/guides/background-fetching-indicators.md, docs/config.json
Query Functions and Data-Fetching Clients
QueryClient does not require a particular transport protocol. The Angular data-fetching guide states that TanStack Query's fetching mechanisms are built agnostically on promises, so applications can use native fetch, graphql-request, Angular HttpClient, or specialized clients. This matters for the reference surface because methods such as fetchQuery, prefetchQuery, and ensureQueryData all ultimately depend on the queryFn supplied in options. The client manages caching, status, retries, invalidation, and observers around that promise, not the low-level HTTP implementation itself.
Sources: docs/framework/angular/angular-httpclient-and-other-data-fetching-clients.md
Angular HttpClient is a useful example because it returns observables today. The guide shows converting an HttpClient request with lastValueFrom inside a queryFn, then using that function in injectQuery. The same promise conversion applies when a query is executed imperatively by the client. The guide also explains why a team might choose HttpClient: testing support through provideHttpClientTesting, Angular interceptors for authentication or logging, PendingTasks integration for unit tests and SSR stability, and built-in SSR request caching.
Sources: docs/framework/angular/angular-httpclient-and-other-data-fetching-clients.md
The same guide also notes that TanStack Query has its own hydration functionality, which may be more powerful than Angular HttpClient SSR caching but requires setup. That distinction is important when choosing between client methods. A route loader might prefetch into the Query cache so the rendered view can hydrate with consistent query state, while an Angular-only HTTP cache may prevent duplicate HTTP requests but not necessarily populate Query cache metadata in the same way. The best choice depends on whether the application needs Query-level lifecycle, invalidation, and observer state after render.
Sources: docs/framework/angular/angular-httpclient-and-other-data-fetching-clients.md
Defaults, Feature Configuration, and Documentation Placement
Default options let teams encode shared behavior once instead of repeating it in every query or mutation. The public API includes app-wide defaults through getDefaultOptions and setDefaultOptions, plus key-scoped defaults through getQueryDefaults, setQueryDefaults, getMutationDefaults, and setMutationDefaults. The official reference example constructs new QueryClient({ defaultOptions: { queries: { staleTime: Infinity } } }), demonstrating that the client is the configuration boundary for cache policy. Framework providers then distribute that configured client to application code.
Sources: docs/framework/angular/reference/functions/provideTanStackQuery.md
The docs configuration shows TanStack Query as a multi-framework documentation site with sections for React, Solid, Vue, Svelte, Lit, Angular, and more. This placement explains why QueryClient should be learned as a core primitive rather than a framework-specific helper. React users import it from @tanstack/react-query, while Angular examples import it from @tanstack/angular-query-experimental; both are exposing the same conceptual client role through adapter packages. When moving across frameworks, keep the QueryClient mental model stable and translate only the provider and observer APIs.
Sources: docs/config.json, docs/framework/angular/reference/functions/provideTanStackQuery.md
Community resources can also influence how teams structure direct client usage. The repository's community page lists tools for generated GraphQL hooks, OpenAPI TypeScript clients, standardized query keys, batching, normalization, and reusable hook kits. Those tools do not replace QueryClient; they usually sit above it by generating query functions, normalizing key conventions, or reducing repetitive cache interaction code. When adopting such tools, verify how they name keys and whether they call setQueryData, invalidation, or prefetch methods on your behalf.
Sources: docs/community-resources.md
Reference Checklist and Next Steps
When you reach for QueryClient, first identify the operation family you need. Use fetch or prefetch methods when the cache needs data before a component observes it. Use read methods when you need to inspect current cache contents. Use write methods for cache seeding, optimistic results, or applying mutation responses. Use invalidation and refetch methods when a server-side change makes existing cached data suspect. Use defaults when many queries share timing, retry, or mutation behavior. Use cache accessors and clear only for lower-level integrations or full lifecycle boundaries.
Sources: docs/framework/angular/reference/functions/provideTanStackQuery.md, docs/framework/angular/guides/background-fetching-indicators.md
A good setup path is concrete: create one QueryClient, configure its defaults, provide it with the adapter's provider API, then add optional features such as devtools. In Angular, that means provideTanStackQuery(new QueryClient(), withDevtools()) for a development-friendly setup, or an InjectionToken if a lazy-loading optimization is worth the complexity. After that, use declarative adapter APIs for most screen data and reserve direct client calls for preloading, invalidation after mutations, cache updates, global activity indicators, persistence, and integration code.
Sources: docs/framework/angular/reference/functions/provideTanStackQuery.md, docs/framework/angular/devtools.md
Related pages to read next: queries for the declarative query model, query-keys for cache identity, prefetching for warming data, invalidations-from-mutations for write flows, devtools for inspection, and core-cache-and-observers-reference for the lower-level caches and observers behind this client-facing API.