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 dataprefetchQuery- Prefetch a query without returning datafetchInfiniteQuery- Fetch an infinite queryprefetchInfiniteQuery- Prefetch an infinite querygetQueryData- Get the cached data for a querysetQueryData- Manually set the cached data for a querygetQueryState- Get the state for a queryinvalidateQueries- Invalidate queries to trigger refetchesrefetchQueries- Refetch queriescancelQueries- Cancel outgoing query requestsremoveQueries- Remove queries from the cacheresetQueries- Reset queries to their initial stateisFetching- Check if any queries are fetchingensureQueryData- Ensure query data exists, fetch if needed
Mutation Methods
getMutationCache- Get the mutation cacheisMutating- Check if any mutations are running
Cache Methods
getQueryCache- Get the query cacheclear- Clear all cache datagetDefaultOptions- Get the default optionssetDefaultOptions- Set the default optionsgetQueryDefaults- Get default options for a query keysetQueryDefaults- Set default options for a query keygetMutationDefaults- Get default options for a mutation keysetMutationDefaults- Set default options for a mutation key
Lifecycle Methods
mount- Mount the QueryClientunmount- 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.