Skip to main content
The useQueryClient hook returns the current QueryClient instance from React context. This allows you to access the QueryClient methods for imperative operations like invalidating queries, setting query data, and more.

Import

Signature

Parameters

QueryClient
Optional QueryClient instance to use instead of the one from context. If provided, this instance will be returned instead of the context value.

Returns

QueryClient
The QueryClient instance with all available methods.

QueryClient Methods

The returned QueryClient provides many methods for interacting with the cache:

Query Methods

  • fetchQuery - Fetch a query and return the data
  • prefetchQuery - Prefetch a query without returning data
  • fetchInfiniteQuery - Fetch an infinite query
  • prefetchInfiniteQuery - Prefetch an infinite query
  • getQueryData - Get the cached data for a query
  • setQueryData - Manually set the cached data for a query
  • getQueryState - Get the state for a query
  • invalidateQueries - Invalidate queries to trigger refetches
  • refetchQueries - Refetch queries
  • cancelQueries - Cancel outgoing query requests
  • removeQueries - Remove queries from the cache
  • resetQueries - Reset queries to their initial state
  • isFetching - Check if any queries are fetching
  • ensureQueryData - Ensure query data exists, fetch if needed

Mutation Methods

  • getMutationCache - Get the mutation cache
  • isMutating - Check if any mutations are running

Cache Methods

  • getQueryCache - Get the query cache
  • clear - Clear all cache data
  • getDefaultOptions - Get the default options
  • setDefaultOptions - Set the default options
  • getQueryDefaults - Get default options for a query key
  • setQueryDefaults - Set default options for a query key
  • getMutationDefaults - Get default options for a mutation key
  • setMutationDefaults - Set default options for a mutation key

Lifecycle Methods

  • mount - Mount the QueryClient
  • unmount - Unmount the QueryClient

Examples

Basic Usage

Invalidating Queries

Manually Setting Query Data

Getting Query Data

Prefetching Queries

Optimistic Updates

Canceling Queries

Removing Queries

Checking Fetching State

Setting Default Options

Ensuring Query Data

Notes

useQueryClient must be used within a component that is wrapped by QueryClientProvider.
If no QueryClientProvider is found in the component tree, the hook will throw an error.
Most QueryClient methods are synchronous except for methods like fetchQuery, prefetchQuery, and cancelQueries which return promises.
The QueryClient instance is stable across renders, so it’s safe to use in dependency arrays.