Coordinate cache operations
A button or event handler needs to invalidate, refetch, or update cached queries.
TanStack · Hook
useQueryClient returns the current React QueryClient. It uses the nearest QueryClientProvider by default, or a supplied QueryClient when one is passed.
In React, useQueryClient retrieves a QueryClient from the nearest QueryClientProvider unless a client is supplied explicitly. The returned client exposes query and mutation cache operations, such as invalidating queries. Calling the hook without an explicit client requires a provider in the component tree.
function useQueryClient(queryClient?: QueryClient): QueryClient;| Name | Type | Description |
|---|---|---|
queryClient | QueryClient | Optional custom client. If omitted, the client from the nearest QueryClientProvider context is used. |
The current QueryClient instance.
import { QueryClient, QueryClientProvider, useQueryClient } from '@tanstack/react-query'
const client = new QueryClient()
function RefreshPosts() {
const queryClient = useQueryClient()
return (
<button onClick={() => queryClient.invalidateQueries({ queryKey: ['posts'] })}>
Refresh posts
</button>
)
}
export default function App() {
return (
<QueryClientProvider client={client}>
<RefreshPosts />
</QueryClientProvider>
)
}The component obtains the provider's QueryClient and uses it to invalidate queries whose key begins with posts.
A button or event handler needs to invalidate, refetch, or update cached queries.
A subtree must use a specifically selected QueryClient rather than the nearest default.
Component logic needs access to the shared query cache without constructing another client.
It returns the current QueryClient instance. With no argument, the hook obtains the client from the nearest QueryClientProvider; passing a QueryClient lets the component use that specific client.
Follow-up: What happens if neither an explicit client nor a provider is available? The hook throws because it cannot resolve a current QueryClient.
The optional argument is a QueryClient. It is useful when the component must operate on a custom client; otherwise, the nearest provider supplies the client.
Follow-up: Why might an application use more than one client? Separate clients can isolate caches, but each component must resolve the intended client rather than accidentally using the nearest default.
The result can call QueryClient methods such as invalidateQueries. This lets event handlers or other component logic coordinate cached data without creating another client instance.
Follow-up: How would you refresh only a subset of cached data? Call invalidateQueries with a matching queryKey filter, as in { queryKey: ['posts'] }.
QueryClientQueryClientProviderinvalidateQueriesuseQuery