Skip to main content

useQueryClient

The useQueryClient hook returns the current QueryClient instance from the React context. It provides access to all QueryClient methods for manual query and mutation management.

Import

Signature

Parameters

QueryClient
Optional QueryClient instance to use. If provided, this client will be returned instead of the context client. Useful for testing or when you want to use a different client instance.

Returns

QueryClient
required
The QueryClient instance from context (or the provided queryClient parameter)

Examples

Basic Usage

Invalidating Queries

Prefetching Queries

Setting Query Data Manually

Accessing Query Cache

Canceling Queries

Removing Queries

Resetting Queries

Accessing Mutation Cache

Building a Refresh Button

With Custom QueryClient

Common Methods

The QueryClient instance provides many useful methods:

Query Methods

  • getQueryData(queryKey) - Get cached query data
  • setQueryData(queryKey, updater) - Set query data manually
  • getQueryState(queryKey) - Get query state information
  • invalidateQueries(filters) - Mark queries as stale
  • refetchQueries(filters) - Refetch queries
  • cancelQueries(filters) - Cancel outgoing queries
  • removeQueries(filters) - Remove queries from cache
  • resetQueries(filters) - Reset queries to initial state
  • prefetchQuery(options) - Prefetch a query
  • fetchQuery(options) - Fetch and return query data

Mutation Methods

  • getMutationCache() - Get the mutation cache instance
  • isMutating(filters) - Check if mutations are running

Cache Methods

  • getQueryCache() - Get the query cache instance
  • clear() - Clear all caches
  • mount() - Mount the client
  • unmount() - Unmount the client

Notes

  • The hook must be used within a QueryClientProvider.
  • If no QueryClient is found in context and none is provided, an error is thrown.
  • The optional queryClient parameter is primarily useful for testing or special use cases.
  • Most query and mutation hooks accept an optional queryClient parameter, making this hook unnecessary in many cases.
  • However, this hook is essential when you need to imperatively interact with the query cache outside of the standard hook lifecycle.