Fetch data imperatively
A route loader or server-side function needs data before rendering.
TanStack · Class
QueryClient is TanStack Query’s imperative interface for interacting with query and mutation caches. It also owns client-level defaults and methods for fetching, reading, updating, and managing cached data.
QueryClient is the imperative entry point for TanStack Query's query and mutation caches. It owns those caches, applies configured defaults, and exposes operations for fetching, reading, updating, invalidating, refetching, cancelling, or removing cached queries.
new QueryClient(config?: QueryClientConfig)| Name | Type | Description |
|---|---|---|
config | QueryClientConfig | Optional configuration containing query and mutation caches plus default options for resources created through the client. |
A QueryClient instance that owns query and mutation caches and exposes cache-management methods.
import { QueryClient } from '@tanstack/react-query'
const queryClient = new QueryClient({
defaultOptions: {
queries: { staleTime: 60_000 },
},
})
await queryClient.fetchQuery({
queryKey: ['todos'],
queryFn: async () => {
const response = await fetch('/api/todos')
if (!response.ok) throw new Error('Request failed')
return response.json()
},
})
const todos = queryClient.getQueryData(['todos'])
console.log(todos)Creates a client with a default query freshness period, fetches and caches a query, then synchronously reads its cached data.
A route loader or server-side function needs data before rendering.
A screen is likely to need data shortly, but should not block the current render.
An event handler must update or invalidate cached resources after a mutation.
QueryClient provides imperative access to TanStack Query's caches. It owns a QueryCache and MutationCache and stores defaults applied to queries and mutations created through it.
Follow-up: How would you avoid an unnecessary network request? Use fetchQuery with a suitable staleTime; it returns cached data while that data is still fresh.
fetchQuery asynchronously fetches and caches a query, returning its data or throwing an error. If matching cached data is not stale according to staleTime, it returns that cached value instead of fetching.
Follow-up: How does this differ from prefetchQuery? prefetchQuery performs the fetch without requiring the caller to use the resulting data.
getQueryData synchronously reads an existing query's cached data. It only reads the cache and returns undefined when the query is absent.
Follow-up: How can several cached queries be inspected together? Use getQueriesData with a query key or query filter to obtain matching entries.
QueryCacheMutationCachefetchQueryprefetchQuerygetQueryDatainvalidateQueriesgetQueryCache