useQueryClient
TheuseQueryClient 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
TheQueryClient instance provides many useful methods:
Query Methods
getQueryData(queryKey)- Get cached query datasetQueryData(queryKey, updater)- Set query data manuallygetQueryState(queryKey)- Get query state informationinvalidateQueries(filters)- Mark queries as stalerefetchQueries(filters)- Refetch queriescancelQueries(filters)- Cancel outgoing queriesremoveQueries(filters)- Remove queries from cacheresetQueries(filters)- Reset queries to initial stateprefetchQuery(options)- Prefetch a queryfetchQuery(options)- Fetch and return query data
Mutation Methods
getMutationCache()- Get the mutation cache instanceisMutating(filters)- Check if mutations are running
Cache Methods
getQueryCache()- Get the query cache instanceclear()- Clear all cachesmount()- Mount the clientunmount()- 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
queryClientparameter is primarily useful for testing or special use cases. - Most query and mutation hooks accept an optional
queryClientparameter, 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.