Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

useQuery.md

513 lines32.5 KB

1---
2id: useQuery
3title: useQuery
4redirect_from:
5 - framework/react/reference/useQuery
6---
7​
8<!-- DO NOT EDIT: this page is autogenerated from the type comments -->
9​
10## Overview
11​
12```ts
13function useQuery<TQueryFnData = unknown, TError = Error, TData = TQueryFnData, TQueryKey extends readonly unknown[] = readonly unknown[]>(options: DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>, queryClient?: QueryClient): DefinedUseQueryResult<TData, TError>;
14function useQuery<TQueryFnData = unknown, TError = Error, TData = TQueryFnData, TQueryKey extends readonly unknown[] = readonly unknown[]>(options: UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>, queryClient?: QueryClient): UseQueryResult<TData, TError>;
15function useQuery<TQueryFnData = unknown, TError = Error, TData = TQueryFnData, TQueryKey extends readonly unknown[] = readonly unknown[]>(options: UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>, queryClient?: QueryClient): UseQueryResult<TData, TError>;
16```
17​
18- [`DefinedInitialDataOptions` β†’ `DefinedUseQueryResult`](#call-signature-1): This overload is selected when `initialData` is known to be defined, so the resulting `data` is typed as never `undefined` (unless a `select` changes `TData` to include `undefined`). At runtime, `data` is still `undefined` if `select` throws on its first call.
19- [`UndefinedInitialDataOptions` β†’ `UseQueryResult`](#call-signature-2): This overload is selected when `initialData` is omitted, may be `undefined`, or is a function that may return `undefined`, so the resulting `data` can be `undefined`.
20- [`UseQueryOptions` β†’ `UseQueryResult`](#call-signature-3): Fallback overload for options whose `initialData` presence isn't statically known β€” for example, an object typed as [UseQueryOptions](../interfaces/UseQueryOptions.md) rather than an object literal. Prefer one of the other overloads when possible, since they infer whether `data` can be `undefined` from `initialData` directly.
21​
22See also: [Parameters](#parameters-summary) Β· [Returns](#returns-summary)
23​
24<a id="call-signature-1"></a>
25​
26## Call Signature
27​
28```ts
29function useQuery<TQueryFnData = unknown, TError = Error, TData = TQueryFnData, TQueryKey extends readonly unknown[] = readonly unknown[]>(options: DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>, queryClient?: QueryClient): DefinedUseQueryResult<TData, TError>;
30```
31​
32Defined in: [packages/react-query/src/useQuery.ts:51](https://github.com/TanStack/query/blob/main/packages/react-query/src/useQuery.ts#L51)
33​
34This overload is selected when `initialData` is known to be defined, so the resulting `data` is typed as never
35`undefined` (unless a `select` changes `TData` to include `undefined`). At runtime, `data` is still `undefined`
36if `select` throws on its first call.
37​
38### Type Parameters
39​
40#### TQueryFnData
41​
42`TQueryFnData` = `unknown`
43​
44#### TError
45​
46`TError` = `Error`
47​
48#### TData
49​
50`TData` = `TQueryFnData`
51​
52#### TQueryKey
53​
54`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
55​
56### Parameters
57​
58#### options
59​
60[`DefinedInitialDataOptions`](../type-aliases/DefinedInitialDataOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>
61​
62The [DefinedInitialDataOptions](../type-aliases/DefinedInitialDataOptions.md) to use β€” everything you can pass to `useQuery`, with `initialData` known to be defined.
63​
64#### queryClient?
65​
66[`QueryClient`](../classes/QueryClient.md)
67​
68Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
69be used.
70​
71### Returns
72​
73[`DefinedUseQueryResult`](../type-aliases/DefinedUseQueryResult.md)\<`TData`, `TError`\>
74​
75The current query result, typed so that `status` is `success` or `error` (`status` never
76resolves to `pending` in this overload's type, since `initialData` guarantees data upfront). `status` is
77`error` if the query has an error from a fetch that failed after its retries or if `select` threw, and
78`success` otherwise. `isSuccess`/`isError` are derived booleans for convenience.
79​
80### See
81​
82[queryOptions](queryOptions.md) to share these options between `useQuery` and imperative APIs like `queryClient.query`.
83​
84### Example
85​
86```tsx
87import { useQuery } from '@tanstack/react-query'
88​
89function Posts() {
90 // `data` is `Post[]`, never `undefined`, thanks to `initialData` β€” even if a refetch fails,
91 // so the list stays visible alongside the error.
92 const { data, isError, error } = useQuery({
93 queryKey: ['posts'],
94 queryFn: fetchPosts,
95 initialData: [],
96 })
97​
98 return (
99 <div>
100 {isError ? <span>Error: {error.message}</span> : null}
101 <ul>
102 {data.map((post) => <li key={post.id}>{post.title}</li>)}
103 </ul>
104 </div>
105 )
107```
108​
109<a id="call-signature-2"></a>
110​
111## Call Signature
112​
113```ts
114function useQuery<TQueryFnData = unknown, TError = Error, TData = TQueryFnData, TQueryKey extends readonly unknown[] = readonly unknown[]>(options: UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>, queryClient?: QueryClient): UseQueryResult<TData, TError>;
115```
116​
117Defined in: [packages/react-query/src/useQuery.ts:119](https://github.com/TanStack/query/blob/main/packages/react-query/src/useQuery.ts#L119)
118​
119This overload is selected when `initialData` is omitted, may be `undefined`, or is a function that may
120return `undefined`, so the resulting `data` can be `undefined`.
121​
122### Type Parameters
123​
124#### TQueryFnData
125​
126`TQueryFnData` = `unknown`
127​
128#### TError
129​
130`TError` = `Error`
131​
132#### TData
133​
134`TData` = `TQueryFnData`
135​
136#### TQueryKey
137​
138`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
139​
140### Parameters
141​
142#### options
143​
144[`UndefinedInitialDataOptions`](../type-aliases/UndefinedInitialDataOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>
145​
146The [UndefinedInitialDataOptions](../type-aliases/UndefinedInitialDataOptions.md) to use β€” everything you can pass to `useQuery`.
147​
148#### queryClient?
149​
150[`QueryClient`](../classes/QueryClient.md)
151​
152Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
153be used.
154​
155### Returns
156​
157[`UseQueryResult`](../type-aliases/UseQueryResult.md)\<`TData`, `TError`\>
158​
159The current query result. `status` is `error` if the query has an error from a fetch that failed
160after its retries or if `select` threw, `success` if the query has cached data (even if `select` returns
161`undefined`) or data from `placeholderData`, and `pending` otherwise. `isPending`/`isSuccess`/`isError`
162are derived booleans for convenience.
163​
164### See
165​
166[queryOptions](queryOptions.md) to share these options between `useQuery` and imperative APIs like `queryClient.query`.
167​
168### Examples
169​
170```tsx
171import { useQuery } from '@tanstack/react-query'
172​
173function Posts() {
174 const { status, data, error, isFetching } = useQuery({
175 queryKey: ['posts'],
176 queryFn: fetchPosts,
177 })
178​
179 if (status === 'pending') return 'Loading...'
180 if (status === 'error') return <span>Error: {error.message}</span>
181​
182 return (
183 <div>
184 <ul>
185 {data.map((post) => (
186 <li key={post.id}>{post.title}</li>
187 ))}
188 </ul>
189 <div>{isFetching ? 'Background Updating...' : ' '}</div>
190 </div>
191 )
193```
194​
195The same query, checking `isPending`/`isError` instead of `status` β€” pick whichever reads better to you:
196```tsx
197import { useQuery } from '@tanstack/react-query'
198​
199function Posts() {
200 const { isPending, isError, data, error } = useQuery({
201 queryKey: ['posts'],
202 queryFn: fetchPosts,
203 })
204​
205 if (isPending) return 'Loading...'
206 if (isError) return <span>Error: {error.message}</span>
207​
208 return (
209 <ul>
210 {data.map((post) => <li key={post.id}>{post.title}</li>)}
211 </ul>
212 )
214```
215​
216<a id="call-signature-3"></a>
217​
218## Call Signature
219​
220```ts
221function useQuery<TQueryFnData = unknown, TError = Error, TData = TQueryFnData, TQueryKey extends readonly unknown[] = readonly unknown[]>(options: UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>, queryClient?: QueryClient): UseQueryResult<TData, TError>;
222```
223​
224Defined in: [packages/react-query/src/useQuery.ts:285](https://github.com/TanStack/query/blob/main/packages/react-query/src/useQuery.ts#L285)
225​
226Fallback overload for options whose `initialData` presence isn't statically known β€” for example, an
227object typed as [UseQueryOptions](../interfaces/UseQueryOptions.md) rather than an object literal. Prefer one of the other overloads
228when possible, since they infer whether `data` can be `undefined` from `initialData` directly.
229​
230### Type Parameters
231​
232#### TQueryFnData
233​
234`TQueryFnData` = `unknown`
235​
236#### TError
237​
238`TError` = `Error`
239​
240#### TData
241​
242`TData` = `TQueryFnData`
243​
244#### TQueryKey
245​
246`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
247​
248### Parameters
249​
250#### options
251​
252[`UseQueryOptions`](../interfaces/UseQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>
253​
254The [UseQueryOptions](../interfaces/UseQueryOptions.md) to use β€” everything you can pass to `useQuery`.
255​
256#### queryClient?
257​
258[`QueryClient`](../classes/QueryClient.md)
259​
260Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
261be used.
262​
263### Returns
264​
265[`UseQueryResult`](../type-aliases/UseQueryResult.md)\<`TData`, `TError`\>
266​
267The current query result. `status` is `error` if the query has an error from a fetch that failed
268after its retries or if `select` threw, `success` if the query has cached data (even if `select` returns
269`undefined`) or data from `placeholderData`, and `pending` otherwise. `isPending`/`isSuccess`/`isError`
270are derived booleans for convenience.
271​
272### See
273​
274[queryOptions](queryOptions.md) to share these options between `useQuery` and imperative APIs like `queryClient.query`.
275​
276### Examples
277​
278```tsx
279import { useQuery } from '@tanstack/react-query'
280​
281function Posts() {
282 const { status, data, error, isFetching } = useQuery({
283 queryKey: ['posts'],
284 queryFn: fetchPosts,
285 })
286​
287 if (status === 'pending') return 'Loading...'
288 if (status === 'error') return <span>Error: {error.message}</span>
289​
290 return (
291 <div>
292 <ul>
293 {data.map((post) => (
294 <li key={post.id}>{post.title}</li>
295 ))}
296 </ul>
297 <div>{isFetching ? 'Background Updating...' : ' '}</div>
298 </div>
299 )
301```
302​
303`select` derives whatever `data` a component needs from the cached value, without changing what's
304actually stored in the cache β€” the cache still holds the full `Post[]`, but `data` here is a `number`:
305```tsx
306import { useQuery } from '@tanstack/react-query'
307​
308function PostCount() {
309 const { data, isPending, isError, error } = useQuery({
310 queryKey: ['posts'],
311 queryFn: fetchPosts,
312 select: (posts) => posts.length,
313 })
314​
315 if (isPending) return 'Loading...'
316 if (isError) return <span>Error: {error.message}</span>
317​
318 return <span>{data} posts</span>
320```
321​
322A dependent query, only enabled once `postId` is set β€” use `isLoading`, not `isPending`, so the
323loading state doesn't show while the query is disabled:
324```tsx
325import { useQuery } from '@tanstack/react-query'
326​
327function Post({ postId }: { postId: number | undefined }) {
328 const { data, isLoading, isError, error } = useQuery({
329 queryKey: ['post', postId],
330 queryFn: () => fetchPost(postId!),
331 enabled: postId != null,
332 })
333​
334 if (postId == null) return 'Select a post'
335 if (isLoading) return 'Loading...'
336 if (isError) return <span>Error: {error.message}</span>
337​
338 return <h1>{data?.title}</h1>
340```
341​
342The same dependent query, type safe: `skipToken` disables the query without needing the
343non-null assertion above, since `queryFn` is only ever called when `postId` is defined.
344`refetch` doesn't work while `queryFn` is `skipToken` β€” use `enabled: false` instead if you
345need to trigger the query manually:
346```tsx
347import { skipToken, useQuery } from '@tanstack/react-query'
348​
349function Post({ postId }: { postId: number | undefined }) {
350 const { data, isLoading, isError, error } = useQuery({
351 queryKey: ['post', postId],
352 queryFn: postId != null ? () => fetchPost(postId) : skipToken,
353 })
354​
355 if (postId == null) return 'Select a post'
356 if (isLoading) return 'Loading...'
357 if (isError) return <span>Error: {error.message}</span>
358​
359 return <h1>{data?.title}</h1>
361```
362​
363Seeding a detail query from an already-cached list, to skip the loading state. `initialDataUpdatedAt` carries
364over the list's own fetch time, so that if you set a `staleTime`, it's measured from when the list was
365fetched rather than from now:
366```tsx
367import { useQuery, useQueryClient } from '@tanstack/react-query'
368​
369function Post({ postId }: { postId: number }) {
370 const queryClient = useQueryClient()
371​
372 const { data, isError, error } = useQuery({
373 queryKey: ['post', postId],
374 queryFn: () => fetchPost(postId),
375 initialData: () =>
376 queryClient
377 .getQueryData<Array<Post>>(['posts'])
378 ?.find((post) => post.id === postId),
379 initialDataUpdatedAt: () =>
380 queryClient.getQueryState(['posts'])?.dataUpdatedAt,
381 })
382​
383 if (isError) return <span>Error: {error.message}</span>
384​
385 return <h1>{data?.title}</h1>
387```
388​
389Paginated data, keeping the previous page's data visible while the next page loads:
390```tsx
391import { keepPreviousData, useQuery } from '@tanstack/react-query'
392import { useState } from 'react'
393​
394function Posts() {
395 const [page, setPage] = useState(0)
396​
397 const { data, isPlaceholderData, isError, error } = useQuery({
398 queryKey: ['posts', page],
399 queryFn: () => fetchPosts(page),
400 placeholderData: keepPreviousData,
401 })
402​
403 if (isError) return <span>Error: {error.message}</span>
404​
405 return (
406 <div>
407 <ul>
408 {data?.map((post) => <li key={post.id}>{post.title}</li>)}
409 </ul>
410 <button
411 disabled={isPlaceholderData}
412 onClick={() => setPage((old) => old + 1)}
413 >
414 Next Page
415 </button>
416 </div>
417 )
419```
420​
421<a id="parameters-summary"></a>
422​
423## Parameters
424​
425### options
426​
427[`UseQueryOptions`](../interfaces/UseQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>
428​
429The [UseQueryOptions](../interfaces/UseQueryOptions.md) to use β€” everything you can pass to `useQuery`.
430​
431<a id="options-properties"></a>
432​
433#### `options` properties
434​
435| Property | Type | Default value | Description |
436| ------ | ------ | ------ | ------ |
437| <a id="options-property-enabled"></a> `enabled?` | \| `false` \| `true` \| ((`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryFnData`, `TQueryKey`\>) => `boolean`) | `true` | Set this to `false` or a function that returns `false` to disable automatic refetching when the query mounts or changes query keys. To refetch the query, use the `refetch` method returned from the `useQuery` instance. Accepts a boolean or function that returns a boolean. |
438| <a id="options-property-gctime"></a> `gcTime?` | `number` | `undefined` | 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 garbage collection times are specified, the longest one will be used. Setting it to `Infinity` will disable garbage collection. Defaults to `5 * 60 * 1000` (5 minutes), or `Infinity` during SSR. Note: the maximum allowed time is about 24 days, imposed by `setTimeout`'s 32-bit signed integer delay β€” see `timeoutManager.setTimeoutProvider` for a workaround. |
439| <a id="options-property-initialdata"></a> `initialData?` | `TQueryFnData` \| (() => `TQueryFnData` \| `undefined`) | `undefined` | 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 initial data. Initial data is considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the cache. |
440| <a id="options-property-initialdataupdatedat"></a> `initialDataUpdatedAt?` | `number` \| (() => `number` \| `undefined`) | `undefined` | If set, this value will be used as the time (in milliseconds) of when the `initialData` itself was last updated. |
441| <a id="options-property-maxpages"></a> `maxPages?` | `number` | `undefined` | Maximum number of pages to store in the data of an infinite query. |
442| <a id="options-property-meta"></a> `meta?` | `Record`\<`string`, `unknown`\> | `undefined` | Additional payload to be stored on each query. Use this property to pass information that can be used in other places. |
443| <a id="options-property-networkmode"></a> `networkMode?` | `"online"` \| `"always"` \| `"offlineFirst"` | `'online'` | Controls whether a query is allowed to run based on the current network connectivity. **See** [Network Mode](https://tanstack.com/query/latest/docs/framework/react/guides/network-mode) for more information. |
444| <a id="options-property-notifyonchangeprops"></a> `notifyOnChangeProps?` | \| `"all"` \| ( \| `"error"` \| `"fetchStatus"` \| `"status"` \| `"data"` \| `"isError"` \| `"isPending"` \| `"isLoading"` \| `"isLoadingError"` \| `"isRefetchError"` \| `"isSuccess"` \| `"isPlaceholderData"` \| `"fetchNextPage"` \| `"fetchPreviousPage"` \| `"hasNextPage"` \| `"hasPreviousPage"` \| `"isFetchNextPageError"` \| `"isFetchingNextPage"` \| `"isFetchPreviousPageError"` \| `"isFetchingPreviousPage"` \| `"dataUpdatedAt"` \| `"errorUpdatedAt"` \| `"failureCount"` \| `"failureReason"` \| `"errorUpdateCount"` \| `"isFetched"` \| `"isFetchedAfterMount"` \| `"isFetching"` \| `"isInitialLoading"` \| `"isPaused"` \| `"isRefetching"` \| `"isStale"` \| `"isEnabled"` \| `"refetch"`)[] \| (() => \| `"all"` \| ( \| `"error"` \| `"fetchStatus"` \| `"status"` \| `"data"` \| `"isError"` \| `"isPending"` \| `"isLoading"` \| `"isLoadingError"` \| `"isRefetchError"` \| `"isSuccess"` \| `"isPlaceholderData"` \| `"fetchNextPage"` \| `"fetchPreviousPage"` \| `"hasNextPage"` \| `"hasPreviousPage"` \| `"isFetchNextPageError"` \| `"isFetchingNextPage"` \| `"isFetchPreviousPageError"` \| `"isFetchingPreviousPage"` \| `"dataUpdatedAt"` \| `"errorUpdatedAt"` \| `"failureCount"` \| `"failureReason"` \| `"errorUpdateCount"` \| `"isFetched"` \| `"isFetchedAfterMount"` \| `"isFetching"` \| `"isInitialLoading"` \| `"isPaused"` \| `"isRefetching"` \| `"isStale"` \| `"isEnabled"` \| `"refetch"`)[] \| `undefined`) | `undefined` | If set, the component will only re-render if any of the listed properties change. When set to `['data', 'error']`, the component will only re-render when the `data` or `error` properties change. When set to `'all'`, the component will re-render whenever a query is updated. When set to a function, the function will be executed to compute the list of properties. Defaults to `undefined`, in which case property access is tracked automatically, and the component only re-renders when one of the tracked properties changes. |
445| <a id="options-property-persister"></a> `persister?` | (`queryFn`: (`context`: `object`) => `TQueryFnData` \| `Promise`\<`TQueryFnData`\>, `context`: `object`, `query`: [`Query`](../classes/Query.md)) => `TQueryFnData` \| `Promise`\<`TQueryFnData`\> | `undefined` | This option can be used to persist the result of a query to an external storage, bypassing the need to actually call the `queryFn`. Useful for persisting a query's data across e.g. server/client boundaries. |
446| <a id="options-property-placeholderdata"></a> `placeholderData?` | \| `NonFunctionGuard`\<`TQueryFnData`\> \| ((`previousData`: `NonFunctionGuard`\<`TQueryFnData`\> \| `undefined`, `previousQuery`: \| [`Query`](../classes/Query.md)\<`NonFunctionGuard`\<`TQueryFnData`\>, `TError`, `NonFunctionGuard`\<`TQueryFnData`\>, `TQueryKey`\> \| `undefined`) => `NonFunctionGuard`\<`TQueryFnData`\> \| `undefined`) | `undefined` | If set, this value will be used as the placeholder data for this particular query observer while the query is still in the `loading` data and no initialData has been provided. |
447| <a id="options-property-queryfn"></a> `queryFn?` | \| *typeof* [`skipToken`](../variables/skipToken.md) \| ((`context`: `object`) => `TQueryFnData` \| `Promise`\<`TQueryFnData`\>) | `undefined` | The function that the query will use to request data. Required, unless a default query function has been set via `queryClient.setQueryDefaults` or `queryClient.setDefaultOptions`. Receives a [QueryFunctionContext](../type-aliases/QueryFunctionContext.md). Must return a promise that will either resolve data or throw an error. The data cannot be `undefined`. |
448| <a id="options-property-queryhash"></a> `queryHash?` | `string` | `undefined` | The hashed form of `queryKey`, computed with `queryKeyHashFn` (or the default hashing function otherwise). Used as the actual cache key internally. |
449| <a id="options-property-querykey"></a> `queryKey` | `TQueryKey` & `object` | `undefined` | The query key to use for this query. The query key will be hashed into a stable hash. See [Query Keys](https://tanstack.com/query/latest/docs/framework/react/guides/query-keys) for more information. The query will automatically update when this key changes (as long as `enabled` is not set to `false`). |
450| <a id="options-property-querykeyhashfn"></a> `queryKeyHashFn?` | (`queryKey`: `TQueryKey`) => `string` | `undefined` | If specified, this function is used to hash the `queryKey` to a string. |
451| <a id="options-property-refetchinterval"></a> `refetchInterval?` | \| `number` \| `false` \| ((`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryFnData`, `TQueryKey`\>) => `number` \| `false` \| `undefined`) | `false` | If set to a number, the query 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 |
452| <a id="options-property-refetchintervalinbackground"></a> `refetchIntervalInBackground?` | `boolean` | `false` | If set to `true`, the query will continue to refetch while their tab/window is in the background. |
453| <a id="options-property-refetchonmount"></a> `refetchOnMount?` | \| `boolean` \| `"always"` \| ((`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryFnData`, `TQueryKey`\>) => `boolean` \| `"always"`) | `true` | If set to `true`, the query will refetch on mount if the data is stale. If set to `false`, will disable additional instances of a query to trigger background refetch. If set to `'always'`, the query will always refetch on mount (except when `staleTime: 'static'` is used). If set to a function, the function will be executed with the latest data and query to compute the value |
454| <a id="options-property-refetchonreconnect"></a> `refetchOnReconnect?` | \| `boolean` \| `"always"` \| ((`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryFnData`, `TQueryKey`\>) => `boolean` \| `"always"`) | `undefined` | 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 (except when `staleTime: 'static'` is used). If set to a function, the function will be executed with the latest data and query to compute the value. Defaults to `true` unless `networkMode` is `'always'`. |
455| <a id="options-property-refetchonwindowfocus"></a> `refetchOnWindowFocus?` | \| `boolean` \| `"always"` \| ((`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryFnData`, `TQueryKey`\>) => `boolean` \| `"always"`) | `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 (except when `staleTime: 'static'` is used). If set to a function, the function will be executed with the latest data and query to compute the value. |
456| <a id="options-property-retry"></a> `retry?` | \| `number` \| `false` \| `true` \| ((`failureCount`: `number`, `error`: `TError`) => `boolean`) | `undefined` | If `false`, failed queries will not retry by default. If `true`, failed queries will retry infinitely. If set to an integer number, e.g. 3, failed queries will retry until the failed query count meets that number. If set to a function `(failureCount, error) => boolean` failed queries will retry until the function returns false. Defaults to `3` on the client and `0` on the server. |
457| <a id="options-property-retrydelay"></a> `retryDelay?` | `number` \| ((`failureCount`: `number`, `error`: `TError`) => `number`) | `undefined` | This function receives a `retryAttempt` integer 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 * 1000` applies linear backoff. Defaults to a function that applies exponential backoff, capped at 30 seconds. |
458| <a id="options-property-retryonmount"></a> `retryOnMount?` | \| `false` \| `true` \| ((`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryFnData`, `TQueryKey`\>) => `boolean`) | `true` | If set to `false`, the query will not be retried on mount if it contains an error. If set to a function, the function will be executed with the query to compute the value. |
459| <a id="options-property-select"></a> `select?` | (`data`: `TQueryFnData`) => `TData` | `undefined` | This option can be used to transform or select a part of the data returned by the query function. It affects the returned `data` value, but does not affect what gets stored in the query cache. The `select` function will only run if `data` changed, or if the reference to the `select` function itself changes. To optimize, memoize the function so its reference stays stable across calls. |
460| <a id="options-property-staletime"></a> `staleTime?` | \| `number` \| `"static"` \| ((`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryFnData`, `TQueryKey`\>) => `number` \| `"static"`) | `0` | The time in milliseconds after data is considered stale. If set to `Infinity`, the data will never be considered stale. If set to `'static'`, the data will never be considered stale. If set to a function, the function will be executed with the query to compute a `staleTime`. |
461| <a id="options-property-structuralsharing"></a> `structuralSharing?` | `boolean` \| ((`oldData`: `unknown`, `newData`: `unknown`) => `unknown`) | `true` | Set this to `false` to disable structural sharing between query results. Set this to a function which accepts the old and new data and returns resolved data of the same type to implement custom structural sharing logic. |
462| <a id="options-property-subscribed"></a> `subscribed?` | `boolean` | `true` | Set this to `false` to unsubscribe this observer from updates to the query cache. |
463| <a id="options-property-throwonerror"></a> `throwOnError?` | \| `false` \| `true` \| ((`error`: `TError`, `query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryFnData`, `TQueryKey`\>) => `boolean`) | `false` | Whether errors should be thrown instead of setting the `error` property. If set to `true` or `suspense` is `true`, all errors will be thrown to the error boundary. If set to `false` and `suspense` is `false`, errors are returned as state. 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`). |
464​
465### queryClient?
466​
467[`QueryClient`](../classes/QueryClient.md)
468​
469Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
470be used.
471​
472<a id="returns-summary"></a>
473​
474## Returns
475​
476[`UseQueryResult`](../type-aliases/UseQueryResult.md)\<`TData`, `TError`\>
477​
478The current query result. `status` is `error` if the query has an error from a fetch that failed
479after its retries or if `select` threw, `success` if the query has cached data (even if `select` returns
480`undefined`) or data from `placeholderData`, and `pending` otherwise. `isPending`/`isSuccess`/`isError`
481are derived booleans for convenience.
482​
483<a id="result-properties"></a>
484​
485### Result properties
486​
487| Property | Type | Description |
488| ------ | ------ | ------ |
489| <a id="result-property-data"></a> `data` | `TData` \| `undefined` | The last successfully resolved data for the query. |
490| <a id="result-property-dataupdatedat"></a> `dataUpdatedAt` | `number` | The timestamp for when the query most recently returned the `status` as `"success"`. |
491| <a id="result-property-error"></a> `error` | `TError` \| `null` | The error object for the query, if an error was thrown. - Defaults to `null`. |
492| <a id="result-property-errorupdatecount"></a> `errorUpdateCount` | `number` | The sum of all errors. |
493| <a id="result-property-errorupdatedat"></a> `errorUpdatedAt` | `number` | The timestamp for when the query most recently returned the `status` as `"error"`. |
494| <a id="result-property-failurecount"></a> `failureCount` | `number` | The failure count for the query. - Incremented every time the query fails. - Reset to `0` when the query succeeds. |
495| <a id="result-property-failurereason"></a> `failureReason` | `TError` \| `null` | The failure reason for the query retry. - Reset to `null` when the query succeeds. |
496| <a id="result-property-fetchstatus"></a> `fetchStatus` | `"idle"` \| `"fetching"` \| `"paused"` | The fetch status of the query. - `fetching`: Is `true` whenever the queryFn is executing, which includes initial `pending` as well as background refetch. - `paused`: The query wanted to fetch, but has been `paused`. - `idle`: The query is not fetching. - See [Network Mode](https://tanstack.com/query/latest/docs/framework/react/guides/network-mode) for more information. |
497| <a id="result-property-isenabled"></a> `isEnabled` | `boolean` | `true` if this observer is enabled, `false` otherwise. |
498| <a id="result-property-iserror"></a> `isError` | `boolean` | A derived boolean from the `status` variable, provided for convenience. - `true` if the query has an error from a fetch that failed after its retries, or if `select` threw. |
499| <a id="result-property-isfetched"></a> `isFetched` | `boolean` | Will be `true` if the query has been fetched. |
500| <a id="result-property-isfetchedaftermount"></a> `isFetchedAfterMount` | `boolean` | Will be `true` if the query has been fetched after the component mounted. - This property can be used to not show any previously cached data. |
501| <a id="result-property-isfetching"></a> `isFetching` | `boolean` | A derived boolean from the `fetchStatus` variable, provided for convenience. - `true` whenever the `queryFn` is executing, which includes initial `pending` as well as background refetch. |
502| <a id="result-property-isinitialloading"></a> ~~`isInitialLoading`~~ | `boolean` | **Deprecated** `isInitialLoading` is being deprecated in favor of `isLoading` and will be removed in the next major version. |
503| <a id="result-property-isloading"></a> `isLoading` | `boolean` | Is `true` whenever the first fetch for a query is in-flight. - Is the same as `isFetching && isPending`. |
504| <a id="result-property-isloadingerror"></a> `isLoadingError` | `boolean` | Will be `true` if the query has an error and no data to display. |
505| <a id="result-property-ispaused"></a> `isPaused` | `boolean` | A derived boolean from the `fetchStatus` variable, provided for convenience. - The query wanted to fetch, but has been `paused`. |
506| <a id="result-property-ispending"></a> `isPending` | `boolean` | Will be `true` if the query has no cached data, no data from `placeholderData` and no error. |
507| <a id="result-property-isplaceholderdata"></a> `isPlaceholderData` | `boolean` | Will be `true` if the data shown is the placeholder data. |
508| <a id="result-property-isrefetcherror"></a> `isRefetchError` | `boolean` | Will be `true` if the query has an error and still has data to display (for infinite queries, not after a failed page fetch). |
509| <a id="result-property-isrefetching"></a> `isRefetching` | `boolean` | Is `true` whenever a background refetch is in-flight, which _does not_ include initial `pending`. - Is the same as `isFetching && !isPending`. |
510| <a id="result-property-isstale"></a> `isStale` | `boolean` | Will be `true` if the data in the cache is invalidated or if the data is older than the given `staleTime`. |
511| <a id="result-property-issuccess"></a> `isSuccess` | `boolean` | A derived boolean from the `status` variable, provided for convenience. - `true` if the query has cached data or data from `placeholderData`, and no error. |
512| <a id="result-property-refetch"></a> `refetch` | (`options?`: [`RefetchOptions`](../interfaces/RefetchOptions.md)) => `Promise`\<[`QueryObserverResult`](../type-aliases/QueryObserverResult.md)\<`TData`, `TError`\>\> | A function to manually refetch the query. |
513| <a id="result-property-status"></a> `status` | `"error"` \| `"pending"` \| `"success"` | The status of the query. - Will be: - `error` if the query has an error from a fetch that failed after its retries, or if `select` threw. - `success` if the query has cached data (even if `select` returns `undefined`) or data from `placeholderData`, and no error. - `pending` otherwise, since the query has no cached data, no data from `placeholderData` and no error. |