useQuery
const {
data,
dataUpdatedAt,
error,
errorUpdatedAt,
failureCount,
isError,
isFetched,
isFetchedAfterMount,
isFetching,
isPaused,
isLoading,
isLoadingError,
isPlaceholderData,
isPreviousData,
isRefetchError,
isRefetching,
isStale,
isSuccess,
refetch,
remove,
status,
fetchStatus,
} = useQuery(queryKey, queryFn?, {
cacheTime,
enabled,
networkMode,
initialData,
initialDataUpdatedAt,
isDataEqual,
keepPreviousData,
meta,
notifyOnChangeProps,
onError,
onSettled,
onSuccess,
placeholderData,
queryKeyHashFn,
refetchInterval,
refetchIntervalInBackground,
refetchOnMount,
refetchOnReconnect,
refetchOnWindowFocus,
retry,
retryOnMount,
retryDelay,
select,
staleTime,
structuralSharing,
suspense,
useErrorBoundary,
})
// or using the object syntax
const result = useQuery({
queryKey,
queryFn,
enabled,
})
Options
queryKey: unknown[]- Required
- The query key to use for this query.
- The query key will be hashed into a stable hash. See Query Keys for more information.
- The query will automatically update when this key changes (as long as
enabledis not set tofalse).
queryFn: (context: QueryFunctionContext) => Promise<TData>- Required, but only if no default query function has been defined See Default Query Function for more information.
- The function that the query will use to request data.
- Receives a QueryFunctionContext
- Must return a promise that will either resolve data or throw an error. The data cannot be
undefined.
enabled: boolean- Set this to
falseto disable this query from automatically running. - Can be used for Dependent Queries.
- Set this to
networkMode: 'online' | 'always' | 'offlineFirst- optional
- defaults to
'online' - see Network Mode for more information.
retry: boolean | number | (failureCount: number, error: TError) => boolean- If
false, failed queries will not retry by default. - If
true, failed queries will retry infinitely. - If set to a
number, e.g.3, failed queries will retry until the failed query count meets that number.
- If
retryOnMount: boolean- If set to
false, the query will not be retried on mount if it contains an error. Defaults totrue.
- If set to
retryDelay: number | (retryAttempt: number, error: TError) => number- This function receives a
retryAttemptinteger and the actual Error and returns the delay to apply before the next attempt in milliseconds. - A function like
attempt => Math.min(attempt > 1 ? 2 ** attempt * 1000 : 1000, 30 * 1000)applies exponential backoff. - A function like
attempt => attempt * 1000applies linear backoff.
- This function receives a
staleTime: number | Infinity- Optional
- Defaults to
0 - The time in milliseconds after data is considered stale. This value only applies to the hook it is defined on.
- If set to
Infinity, the data will never be considered stale
cacheTime: number | Infinity- Defaults to
5 * 60 * 1000(5 minutes) orInfinityduring SSR - The time in milliseconds that unused/inactive cache data remains in memory. When a query's cache becomes unused or inactive, that cache data will be garbage collected after this duration. When different cache times are specified, the longest one will be used.
- If set to
Infinity, will disable garbage collection
- Defaults to
queryKeyHashFn: (queryKey: QueryKey) => string- Optional
- If specified, this function is used to hash the
queryKeyto a string.
refetchInterval: number | false | ((data: TData | undefined, query: Query) => number | false)- Optional
- If set to a number, all queries will continuously refetch at this frequency in milliseconds
- If set to a function, the function will be executed with the latest data and query to compute a frequency
refetchIntervalInBackground: boolean- Optional
- If set to
true, queries that are set to continuously refetch with arefetchIntervalwill continue to refetch while their tab/window is in the background
refetchOnMount: boolean | "always" | ((query: Query) => boolean | "always")- Optional
- Defaults to
true - If set to
true, the query will refetch on mount if the data is stale. - If set to
false, the query will not refetch on mount. - If set to
"always", the query will always refetch on mount. - If set to a function, the function will be executed with the query to compute the value
refetchOnWindowFocus: boolean | "always" | ((query: Query) => boolean | "always")- Optional
- Defaults to
true - If set to
true, the query will refetch on window focus if the data is stale. - If set to
false, the query will not refetch on window focus. - If set to
"always", the query will always refetch on window focus. - If set to a function, the function will be executed with the query to compute the value
refetchOnReconnect: boolean | "always" | ((query: Query) => boolean | "always")- Optional
- Defaults to
true - If set to
true, the query will refetch on reconnect if the data is stale. - If set to
false, the query will not refetch on reconnect. - If set to
"always", the query will always refetch on reconnect. - If set to a function, the function will be executed with the query to compute the value
notifyOnChangeProps: string[] | "all"- Optional
- If set, the component will only re-render if any of the listed properties change.
- If set to
['data', 'error']for example, the component will only re-render when thedataorerrorproperties change. - If set to
"all", the component will opt-out of smart tracking and re-render whenever a query is updated. - By default, access to properties will be tracked, and the component will only re-render when one of the tracked properties change.
onSuccess: (data: TData) => void- Optional
- This function will fire any time the query successfully fetches new data.
onError: (error: TError) => void- Optional
- This function will fire if the query encounters an error and will be passed the error.
onSettled: (data?: TData, error?: TError) => void- Optional
- This function will fire any time the query is either successfully fetched or errors and be passed either the data or error.
select: (data: TData) => unknown- Optional
- This option can be used to transform or select a part of the data returned by the query function. It affects the returned
datavalue, but does not affect what gets stored in the query cache.
suspense: boolean- Optional
- Set this to
trueto enable suspense mode. - When
true,useQuerywill suspend whenstatus === 'loading' - When
true,useQuerywill throw runtime errors whenstatus === 'error'
initialData: TData | () => TData- Optional
- If set, this value will be used as the initial data for the query cache (as long as the query hasn't been created or cached yet)
- If set to a function, the function will be called once during the shared/root query initialization, and be expected to synchronously return the initialData
- Initial data is considered stale by default unless a
staleTimehas been set. initialDatais persisted to the cache
initialDataUpdatedAt: number | (() => number | undefined)- Optional
- If set, this value will be used as the time (in milliseconds) of when the
initialDataitself was last updated.
placeholderData: TData | () => TData- Optional
- If set, this value will be used as the placeholder data for this particular query observer while the query is still in the
loadingdata and no initialData has been provided. placeholderDatais not persisted to the cache
keepPreviousData: boolean- Optional
- Defaults to
false - If set, any previous
datawill be kept when fetching new data because the query key changed.
isDataEqual: (oldData: TData | undefined, newData: TData) => boolean- Optional
- This function should return boolean indicating whether to use previous
data(true) or new data (false) as a resolved data for the query.
structuralSharing: boolean- Optional
- Defaults to
true - If set to
false, structural sharing between query results will be disabled.
useErrorBoundary: undefined | boolean | (error: TError, query: Query) => boolean- Defaults to the global query config's
useErrorBoundaryvalue, which isundefined - Set this to
trueif you want errors to be thrown in the render phase and propagate to the nearest error boundary - Set this to
falseto disablesuspense's default behavior of throwing errors to the error boundary. - If set to a function, it will be passed the error and the query, and it should return a boolean indicating whether to show the error in an error boundary (
true) or return the error as state (false)
- Defaults to the global query config's
meta: Record<string, unknown>- Optional
- If set, stores additional information on the query cache entry that can be used as needed. It will be accessible wherever the
queryis available, and is also part of theQueryFunctionContextprovided to thequeryFn.
context?: React.Context<QueryClient | undefined>- Use this to use a custom React Query context. Otherwise,
defaultContextwill be used.
- Use this to use a custom React Query context. Otherwise,
Returns
status: String- Will be:
loadingif the query is in a "hard" loading state. This means there is no cached data and the query is currently fetching, egisFetching === trueerrorif the query attempt resulted in an error. The correspondingerrorproperty has the error received from the attempted fetchsuccessif the query has received a response with no errors and is ready to display its data. The correspondingdataproperty on the query is the data received from the successful fetch or if the query'senabledproperty is set tofalseand has not been fetched yetdatais the firstinitialDatasupplied to the query on initialization.
- Will be:
isLoading: boolean- A derived boolean from the
statusvariable above, provided for convenience.
- A derived boolean from the
isSuccess: boolean- A derived boolean from the
statusvariable above, provided for convenience.
- A derived boolean from the
isError: boolean- A derived boolean from the
statusvariable above, provided for convenience.
- A derived boolean from the
isLoadingError: boolean- Will be
trueif the query failed while fetching for the first time.
- Will be
isRefetchError: boolean- Will be
trueif the query failed while refetching.
- Will be
data: TData- Defaults to
undefined. - The last successfully resolved data for the query.
- Defaults to
dataUpdatedAt: number- The timestamp for when the query most recently returned the
statusas"success".
- The timestamp for when the query most recently returned the
error: null | TError- Defaults to
null - The error object for the query, if an error was thrown.
- Defaults to
errorUpdatedAt: number- The timestamp for when the query most recently returned the
statusas"error".
- The timestamp for when the query most recently returned the
isStale: boolean- Will be
trueif the data in the cache is invalidated or if the data is older than the givenstaleTime.
- Will be
isPlaceholderData: boolean- Will be
trueif the data shown is the placeholder data.
- Will be
isPreviousData: boolean- Will be
truewhenkeepPreviousDatais set and data from the previous query is returned.
- Will be
isFetched: boolean- Will be
trueif the query has been fetched.
- Will be
isFetchedAfterMount: boolean- Will be
trueif the query has been fetched after the component mounted. - This property can be used to not show any previously cached data.
- Will be
fetchStatus: FetchStatusfetching: Istruewhenever the queryFn is executing, which includes initialloadingas well as background refetches.paused: The query wanted to fetch, but has beenpaused.idle: The query is not fetching.- see Network Mode for more information.
isFetching: boolean- A derived boolean from the
fetchStatusvariable above, provided for convenience.
- A derived boolean from the
isPaused: boolean- A derived boolean from the
fetchStatusvariable above, provided for convenience.
- A derived boolean from the
isRefetching: boolean- Is
truewhenever a background refetch is in-flight, which does not include initialloading - Is the same as
isFetching && !isLoading
- Is
failureCount: number- The failure count for the query.
- Incremented every time the query fails.
- Reset to
0when the query succeeds.
errorUpdateCount: number- The sum of all errors.
refetch: (options: { throwOnError: boolean, cancelRefetch: boolean }) => Promise<UseQueryResult>- A function to manually refetch the query.
- If the query errors, the error will only be logged. If you want an error to be thrown, pass the
throwOnError: trueoption cancelRefetch?: boolean- Defaults to
true- Per default, a currently running request will be cancelled before a new request is made
- When set to
false, no refetch will be made if there is already a request running.
- Defaults to
remove: () => void- A function to remove the query from the cache.