Skip to main content

Overview

The QueryClient is the core class that manages queries, mutations, and their caches. It provides methods for fetching, caching, and synchronizing data throughout your application.

Constructor

const queryClient = new QueryClient(config?: QueryClientConfig)
config
QueryClientConfig
Configuration options for the QueryClient

Methods

mount()

Mounts the QueryClient, setting up listeners for focus and online events.
queryClient.mount(): void
This method is called automatically when using framework adapters like React Query. Manual invocation is typically not needed.

unmount()

Unmounts the QueryClient and cleans up listeners.
queryClient.unmount(): void

fetchQuery()

Fetches a query and returns a promise that resolves with the data.
const data = await queryClient.fetchQuery<TQueryFnData, TError, TData, TQueryKey>({
  queryKey: TQueryKey,
  queryFn: QueryFunction<TQueryFnData, TQueryKey>,
  // ... other options
})
options
FetchQueryOptions<TQueryFnData, TError, TData, TQueryKey>
required
Returns: Promise<TData> Example:
const data = await queryClient.fetchQuery({
  queryKey: ['todos'],
  queryFn: async () => {
    const response = await fetch('/api/todos')
    return response.json()
  },
})

prefetchQuery()

Prefetches a query and caches the result. Does not return data or throw errors.
await queryClient.prefetchQuery(options: FetchQueryOptions): Promise<void>
Example:
await queryClient.prefetchQuery({
  queryKey: ['todos'],
  queryFn: fetchTodos,
})

fetchInfiniteQuery()

Fetches an infinite query with pagination support.
const data = await queryClient.fetchInfiniteQuery<TQueryFnData, TError, TData, TQueryKey, TPageParam>({
  queryKey: TQueryKey,
  queryFn: QueryFunction<TQueryFnData, TQueryKey, TPageParam>,
  initialPageParam: TPageParam,
  getNextPageParam: (lastPage, allPages, lastPageParam, allPageParams) => TPageParam | undefined | null,
  getPreviousPageParam?: (firstPage, allPages, firstPageParam, allPageParams) => TPageParam | undefined | null,
})
Returns: Promise<InfiniteData<TData, TPageParam>>

prefetchInfiniteQuery()

Prefetches an infinite query.
await queryClient.prefetchInfiniteQuery(options: FetchInfiniteQueryOptions): Promise<void>

getQueryData()

Returns the cached data for a query, or undefined if the query does not exist.
const data = queryClient.getQueryData<TQueryFnData>(queryKey: QueryKey): TQueryFnData | undefined
This is a non-reactive way to retrieve data. Use useQuery in React components to subscribe to changes.
Example:
const todos = queryClient.getQueryData(['todos'])

setQueryData()

Updates the cached data for a query.
queryClient.setQueryData<TQueryFnData>(
  queryKey: QueryKey,
  updater: TQueryFnData | undefined | ((oldData: TQueryFnData | undefined) => TQueryFnData | undefined),
  options?: SetDataOptions
): TQueryFnData | undefined
queryKey
QueryKey
required
Query key to update
updater
TQueryFnData | Updater<TQueryFnData>
required
New data or function that receives old data and returns new data
options
SetDataOptions
Example:
queryClient.setQueryData(['todos'], (old) => [...old, newTodo])

getQueriesData()

Returns cached data for multiple queries matching the filters.
const queries = queryClient.getQueriesData<TQueryFnData>(filters: QueryFilters): Array<[QueryKey, TQueryFnData | undefined]>
Returns: Array of [queryKey, data] tuples

setQueriesData()

Updates cached data for multiple queries matching the filters.
queryClient.setQueriesData<TQueryFnData>(
  filters: QueryFilters,
  updater: TQueryFnData | Updater<TQueryFnData>,
  options?: SetDataOptions
): Array<[QueryKey, TQueryFnData | undefined]>

getQueryState()

Returns the full state of a query.
const state = queryClient.getQueryState<TQueryFnData, TError>(queryKey: QueryKey): QueryState<TQueryFnData, TError> | undefined
QueryState
object

ensureQueryData()

Ensures that query data is available. If data exists and is not stale, it returns the cached data. Otherwise, it fetches the data.
const data = await queryClient.ensureQueryData(options: EnsureQueryDataOptions): Promise<TData>
options.revalidateIfStale
boolean
If true, will refetch in the background if data is stale. Defaults to false.

invalidateQueries()

Marks queries as stale and optionally refetches them.
await queryClient.invalidateQueries(
  filters?: InvalidateQueryFilters,
  options?: InvalidateOptions
): Promise<void>
filters
InvalidateQueryFilters
Example:
// Invalidate all queries
await queryClient.invalidateQueries()

// Invalidate specific queries
await queryClient.invalidateQueries({ queryKey: ['todos'] })

// Invalidate without refetching
await queryClient.invalidateQueries(
  { queryKey: ['todos'] },
  { refetchType: 'none' }
)

refetchQueries()

Refetches queries that match the filters.
await queryClient.refetchQueries(
  filters?: RefetchQueryFilters,
  options?: RefetchOptions
): Promise<void>
options
RefetchOptions

cancelQueries()

Cancels ongoing queries that match the filters.
await queryClient.cancelQueries(
  filters?: QueryFilters,
  options?: CancelOptions
): Promise<void>
options.revert
boolean
Revert the query to its previous state. Defaults to true.
Example:
await queryClient.cancelQueries({ queryKey: ['todos'] })

removeQueries()

Removes queries from the cache.
queryClient.removeQueries(filters?: QueryFilters): void
Example:
queryClient.removeQueries({ queryKey: ['todos'], exact: true })

resetQueries()

Resets queries to their initial state and optionally refetches them.
await queryClient.resetQueries(
  filters?: QueryFilters,
  options?: ResetOptions
): Promise<void>

isFetching()

Returns the number of queries that are currently fetching.
const count = queryClient.isFetching(filters?: QueryFilters): number

isMutating()

Returns the number of mutations that are currently pending.
const count = queryClient.isMutating(filters?: MutationFilters): number

getQueryCache()

Returns the QueryCache instance.
const queryCache = queryClient.getQueryCache(): QueryCache

getMutationCache()

Returns the MutationCache instance.
const mutationCache = queryClient.getMutationCache(): MutationCache

getDefaultOptions()

Returns the default options for the QueryClient.
const options = queryClient.getDefaultOptions(): DefaultOptions

setDefaultOptions()

Sets default options for all queries and mutations.
queryClient.setDefaultOptions(options: DefaultOptions): void
Example:
queryClient.setDefaultOptions({
  queries: {
    staleTime: 1000 * 60 * 5, // 5 minutes
    gcTime: 1000 * 60 * 10, // 10 minutes
  },
})

setQueryDefaults()

Sets default options for queries with specific query keys.
queryClient.setQueryDefaults(
  queryKey: QueryKey,
  options: Partial<QueryObserverOptions>
): void
Example:
queryClient.setQueryDefaults(['todos'], {
  staleTime: 1000 * 10,
})

getQueryDefaults()

Returns the default options for a specific query key.
const defaults = queryClient.getQueryDefaults(queryKey: QueryKey): Partial<QueryObserverOptions>

setMutationDefaults()

Sets default options for mutations with specific mutation keys.
queryClient.setMutationDefaults(
  mutationKey: MutationKey,
  options: MutationObserverOptions
): void

getMutationDefaults()

Returns the default options for a specific mutation key.
const defaults = queryClient.getMutationDefaults(mutationKey: MutationKey): MutationObserverOptions

resumePausedMutations()

Resumes all paused mutations.
await queryClient.resumePausedMutations(): Promise<unknown>

clear()

Clears all queries and mutations from the cache.
queryClient.clear(): void
This will remove all data from the cache and should be used with caution.

Type Parameters

Most methods accept the following type parameters:
  • TQueryFnData - The type of data returned by the query function
  • TError - The type of error that can be thrown (defaults to DefaultError)
  • TData - The type of data after selection/transformation
  • TQueryKey - The type of the query key
  • TPageParam - The type of the page parameter for infinite queries

Build docs developers (and LLMs) love