usePrefetchQuery
TheusePrefetchQuery hook allows you to prefetch a query during component render. This is useful for prefetching data that you know will be needed soon, such as when hovering over a link.
Import
Signature
Type Parameters
type
default:"unknown"
The type of data returned by the query function
type
default:"DefaultError"
The type of error that can be thrown by the query function
type
default:"TQueryFnData"
The type of data after transformation
type
default:"QueryKey"
The type of the query key
Parameters
UsePrefetchQueryOptions
required
Configuration options for the query to prefetch. Accepts the same options as
useQuery.TQueryKey
required
A unique key for the query. Must be an array.
QueryFunction<TQueryFnData, TQueryKey>
required
The function that will be called to fetch data.
number | ((query: Query) => number)
Time in milliseconds after data is considered stale
number
Time in milliseconds that unused/inactive cache data remains in memory
QueryClient
Optional QueryClient instance to use. If not provided, the context client is used.
Returns
This hook does not return anything (void). It only triggers a prefetch if the query does not already exist in the cache.
Examples
Basic Usage
Prefetch on Hover
With Custom Stale Time
List with Prefetching
Notes
- The hook only prefetches if the query doesn’t already exist in the cache (checked via
queryClient.getQueryState). - This hook is designed to be used during render, making it safe to use in component bodies.
- For event-based prefetching (like onClick), consider using
queryClient.prefetchQuerydirectly instead. - The prefetch is fire-and-forget; you don’t get access to the loading state or data.
- If you need to access the query state, use
useQueryinstead.