Open History to see the last commit
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 never `undefined` (unless a `select` changes `TData` to include `undefined`).
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:49](https://github.com/TanStack/query/blob/main/packages/react-query/src/useQuery.ts#L49)
33β
34This overload is selected when `initialData` is known to be defined, so the resulting `data` is never
35`undefined` (unless a `select` changes `TData` to include `undefined`).
36β
37### Type Parameters
38β
39#### TQueryFnData
40β
41`TQueryFnData` = `unknown`
42β
43#### TError
44β
45`TError` = `Error`
46β
47#### TData
48β
49`TData` = `TQueryFnData`
50β
51#### TQueryKey
52β
53`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
54β
55### Parameters
56β
57#### options
58β
59[`DefinedInitialDataOptions`](../type-aliases/DefinedInitialDataOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>
60β
61The [DefinedInitialDataOptions](../type-aliases/DefinedInitialDataOptions.md) to use β everything you can pass to `useQuery`, with `initialData` known to be defined.
62β
63#### queryClient?
64β
65[`QueryClient`](../classes/QueryClient.md)
66β
67Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
68be used.
69β
70### Returns
71β
72[`DefinedUseQueryResult`](../type-aliases/DefinedUseQueryResult.md)\<`TData`, `TError`\>
73β
74The current query result, typed so that `status` is `success` β or `error` if a fetch attempt
75fails while keeping the existing data (`status` never resolves to `pending` in this overload's type,
76since `initialData` guarantees data upfront). `isSuccess`/`isError` are derived booleans for convenience.
77β
78### See
79β
80[queryOptions](queryOptions.md) to share these options between `useQuery` and imperative APIs like `queryClient.query`.
81β
82### Example
83β
84```tsx
85import { useQuery } from '@tanstack/react-query'
86β
87function Posts() {
88 // `data` is `Post[]`, never `undefined`, thanks to `initialData` β even if a refetch fails,
89 // so the list stays visible alongside the error.
90 const { data, isError, error } = useQuery({
91 queryKey: ['posts'],
92 queryFn: fetchPosts,
93 initialData: [],
94 })
95β
96 return (
97 <div>
98 {isError ? <span>Error: {error.message}</span> : null}
99 <ul>
100 {data.map((post) => <li key={post.id}>{post.title}</li>)}
101 </ul>
102 </div>
103 )
104}
105```
106β
107<a id="call-signature-2"></a>
108β
109## Call Signature
110β
111```ts
112function useQuery<TQueryFnData = unknown, TError = Error, TData = TQueryFnData, TQueryKey extends readonly unknown[] = readonly unknown[]>(options: UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>, queryClient?: QueryClient): UseQueryResult<TData, TError>;
113```
114β
115Defined in: [packages/react-query/src/useQuery.ts:116](https://github.com/TanStack/query/blob/main/packages/react-query/src/useQuery.ts#L116)
116β
117This overload is selected when `initialData` is omitted, may be `undefined`, or is a function that may
118return `undefined`, so the resulting `data` can be `undefined`.
119β
120### Type Parameters
121β
122#### TQueryFnData
123β
124`TQueryFnData` = `unknown`
125β
126#### TError
127β
128`TError` = `Error`
129β
130#### TData
131β
132`TData` = `TQueryFnData`
133β
134#### TQueryKey
135β
136`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
137β
138### Parameters
139β
140#### options
141β
142[`UndefinedInitialDataOptions`](../type-aliases/UndefinedInitialDataOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>
143β
144The [UndefinedInitialDataOptions](../type-aliases/UndefinedInitialDataOptions.md) to use β everything you can pass to `useQuery`.
145β
146#### queryClient?
147β
148[`QueryClient`](../classes/QueryClient.md)
149β
150Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
151be used.
152β
153### Returns
154β
155[`UseQueryResult`](../type-aliases/UseQueryResult.md)\<`TData`, `TError`\>
156β
157The current query result. `status` is `pending` if there is no cached data to display, `error` if
158the last fetch attempt failed, or `success` if the query has data to display. `isPending`/`isSuccess`/`isError`
159are derived booleans for convenience.
160β
161### See
162β
163[queryOptions](queryOptions.md) to share these options between `useQuery` and imperative APIs like `queryClient.query`.
164β
165### Examples
166β
167```tsx
168import { useQuery } from '@tanstack/react-query'
169β
170function Posts() {
171 const { status, data, error, isFetching } = useQuery({
172 queryKey: ['posts'],
173 queryFn: fetchPosts,
174 })
175β
176 if (status === 'pending') return 'Loading...'
177 if (status === 'error') return <span>Error: {error.message}</span>
178β
179 return (
180 <div>
181 <ul>
182 {data.map((post) => (
183 <li key={post.id}>{post.title}</li>
184 ))}
185 </ul>
186 <div>{isFetching ? 'Background Updating...' : ' '}</div>
187 </div>
188 )
189}
190```
191β
192The same query, checking `isPending`/`isError` instead of `status` β pick whichever reads better to you:
193```tsx
194import { useQuery } from '@tanstack/react-query'
195β
196function Posts() {
197 const { isPending, isError, data, error } = useQuery({
198 queryKey: ['posts'],
199 queryFn: fetchPosts,
200 })
201β
202 if (isPending) return 'Loading...'
203 if (isError) return <span>Error: {error.message}</span>
204β
205 return (
206 <ul>
207 {data.map((post) => <li key={post.id}>{post.title}</li>)}
208 </ul>
209 )
210}
211```
212β
213<a id="call-signature-3"></a>
214β
215## Call Signature
216β
217```ts
218function useQuery<TQueryFnData = unknown, TError = Error, TData = TQueryFnData, TQueryKey extends readonly unknown[] = readonly unknown[]>(options: UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>, queryClient?: QueryClient): UseQueryResult<TData, TError>;
219```
220β
221Defined in: [packages/react-query/src/useQuery.ts:281](https://github.com/TanStack/query/blob/main/packages/react-query/src/useQuery.ts#L281)
222β
223Fallback overload for options whose `initialData` presence isn't statically known β for example, an
224object typed as [UseQueryOptions](../interfaces/UseQueryOptions.md) rather than an object literal. Prefer one of the other overloads
225when possible, since they infer whether `data` can be `undefined` from `initialData` directly.
226β
227### Type Parameters
228β
229#### TQueryFnData
230β
231`TQueryFnData` = `unknown`
232β
233#### TError
234β
235`TError` = `Error`
236β
237#### TData
238β
239`TData` = `TQueryFnData`
240β
241#### TQueryKey
242β
243`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
244β
245### Parameters
246β
247#### options
248β
249[`UseQueryOptions`](../interfaces/UseQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>
250β
251The [UseQueryOptions](../interfaces/UseQueryOptions.md) to use β everything you can pass to `useQuery`.
252β
253#### queryClient?
254β
255[`QueryClient`](../classes/QueryClient.md)
256β
257Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
258be used.
259β
260### Returns
261β
262[`UseQueryResult`](../type-aliases/UseQueryResult.md)\<`TData`, `TError`\>
263β
264The current query result. `status` is `pending` if there is no cached data to display, `error` if
265the last fetch attempt failed, or `success` if the query has data to display. `isPending`/`isSuccess`/`isError`
266are derived booleans for convenience.
267β
268### See
269β
270[queryOptions](queryOptions.md) to share these options between `useQuery` and imperative APIs like `queryClient.query`.
271β
272### Examples
273β
274```tsx
275import { useQuery } from '@tanstack/react-query'
276β
277function Posts() {
278 const { status, data, error, isFetching } = useQuery({
279 queryKey: ['posts'],
280 queryFn: fetchPosts,
281 })
282β
283 if (status === 'pending') return 'Loading...'
284 if (status === 'error') return <span>Error: {error.message}</span>
285β
286 return (
287 <div>
288 <ul>
289 {data.map((post) => (
290 <li key={post.id}>{post.title}</li>
291 ))}
292 </ul>
293 <div>{isFetching ? 'Background Updating...' : ' '}</div>
294 </div>
295 )
296}
297```
298β
299`select` derives whatever `data` a component needs from the cached value, without changing what's
300actually stored in the cache β the cache still holds the full `Post[]`, but `data` here is a `number`:
301```tsx
302import { useQuery } from '@tanstack/react-query'
303β
304function PostCount() {
305 const { data, isPending, isError, error } = useQuery({
306 queryKey: ['posts'],
307 queryFn: fetchPosts,
308 select: (posts) => posts.length,
309 })
310β
311 if (isPending) return 'Loading...'
312 if (isError) return <span>Error: {error.message}</span>
313β
314 return <span>{data} posts</span>
315}
316```
317β
318A dependent query, only enabled once `postId` is set β use `isLoading`, not `isPending`, so the
319loading state doesn't show while the query is disabled:
320```tsx
321import { useQuery } from '@tanstack/react-query'
322β
323function Post({ postId }: { postId: number | undefined }) {
324 const { data, isLoading, isError, error } = useQuery({
325 queryKey: ['post', postId],
326 queryFn: () => fetchPost(postId!),
327 enabled: postId != null,
328 })
329β
330 if (postId == null) return 'Select a post'
331 if (isLoading) return 'Loading...'
332 if (isError) return <span>Error: {error.message}</span>
333β
334 return <h1>{data?.title}</h1>
335}
336```
337β
338The same dependent query, type safe: `skipToken` disables the query without needing the
339non-null assertion above, since `queryFn` is only ever called when `postId` is defined.
340`refetch` doesn't work while `queryFn` is `skipToken` β use `enabled: false` instead if you
341need to trigger the query manually:
342```tsx
343import { skipToken, useQuery } from '@tanstack/react-query'
344β
345function Post({ postId }: { postId: number | undefined }) {
346 const { data, isLoading, isError, error } = useQuery({
347 queryKey: ['post', postId],
348 queryFn: postId != null ? () => fetchPost(postId) : skipToken,
349 })
350β
351 if (postId == null) return 'Select a post'
352 if (isLoading) return 'Loading...'
353 if (isError) return <span>Error: {error.message}</span>
354β
355 return <h1>{data?.title}</h1>
356}
357```
358β
359Seeding a detail query from an already-cached list, to skip the loading state. `initialDataUpdatedAt` carries
360over the list's own fetch time, so that if you set a `staleTime`, it's measured from when the list was
361fetched rather than from now:
362```tsx
363import { useQuery, useQueryClient } from '@tanstack/react-query'
364β
365function Post({ postId }: { postId: number }) {
366 const queryClient = useQueryClient()
367β
368 const { data, isError, error } = useQuery({
369 queryKey: ['post', postId],
370 queryFn: () => fetchPost(postId),
371 initialData: () =>
372 queryClient
373 .getQueryData<Array<Post>>(['posts'])
374 ?.find((post) => post.id === postId),
375 initialDataUpdatedAt: () =>
376 queryClient.getQueryState(['posts'])?.dataUpdatedAt,
377 })
378β
379 if (isError) return <span>Error: {error.message}</span>
380β
381 return <h1>{data?.title}</h1>
382}
383```
384β
385Paginated data, keeping the previous page's data visible while the next page loads:
386```tsx
387import { keepPreviousData, useQuery } from '@tanstack/react-query'
388import { useState } from 'react'
389β
390function Posts() {
391 const [page, setPage] = useState(0)
392β
393 const { data, isPlaceholderData, isError, error } = useQuery({
394 queryKey: ['posts', page],
395 queryFn: () => fetchPosts(page),
396 placeholderData: keepPreviousData,
397 })
398β
399 if (isError) return <span>Error: {error.message}</span>
400β
401 return (
402 <div>
403 <ul>
404 {data?.map((post) => <li key={post.id}>{post.title}</li>)}
405 </ul>
406 <button
407 disabled={isPlaceholderData}
408 onClick={() => setPage((old) => old + 1)}
409 >
410 Next Page
411 </button>
412 </div>
413 )
414}
415```
416β
417<a id="parameters-summary"></a>
418β
419## Parameters
420β
421### options
422β
423[`UseQueryOptions`](../interfaces/UseQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>
424β
425The [UseQueryOptions](../interfaces/UseQueryOptions.md) to use β everything you can pass to `useQuery`.
426β
427<a id="options-properties"></a>
428β
429#### `options` properties
430β
431| Property | Type | Default value | Description |
432| ------ | ------ | ------ | ------ |
433| <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. |
434| <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. |
435| <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. |
436| <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. |
437| <a id="options-property-maxpages"></a> `maxPages?` | `number` | `undefined` | Maximum number of pages to store in the data of an infinite query. |
438| <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. |
439| <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. |
440| <a id="options-property-notifyonchangeprops"></a> `notifyOnChangeProps?` | \| ( \| `"error"` \| `"data"` \| `"isError"` \| `"isPending"` \| `"isLoading"` \| `"isLoadingError"` \| `"isRefetchError"` \| `"isSuccess"` \| `"isPlaceholderData"` \| `"status"` \| `"dataUpdatedAt"` \| `"errorUpdatedAt"` \| `"failureCount"` \| `"failureReason"` \| `"errorUpdateCount"` \| `"isFetched"` \| `"isFetchedAfterMount"` \| `"isFetching"` \| `"isInitialLoading"` \| `"isPaused"` \| `"isRefetching"` \| `"isStale"` \| `"isEnabled"` \| `"refetch"` \| `"fetchStatus"` \| `"fetchNextPage"` \| `"fetchPreviousPage"` \| `"hasNextPage"` \| `"hasPreviousPage"` \| `"isFetchNextPageError"` \| `"isFetchingNextPage"` \| `"isFetchPreviousPageError"` \| `"isFetchingPreviousPage"`)[] \| `"all"` \| (() => \| `"all"` \| ( \| `"error"` \| `"data"` \| `"isError"` \| `"isPending"` \| `"isLoading"` \| `"isLoadingError"` \| `"isRefetchError"` \| `"isSuccess"` \| `"isPlaceholderData"` \| `"status"` \| `"dataUpdatedAt"` \| `"errorUpdatedAt"` \| `"failureCount"` \| `"failureReason"` \| `"errorUpdateCount"` \| `"isFetched"` \| `"isFetchedAfterMount"` \| `"isFetching"` \| `"isInitialLoading"` \| `"isPaused"` \| `"isRefetching"` \| `"isStale"` \| `"isEnabled"` \| `"refetch"` \| `"fetchStatus"` \| `"fetchNextPage"` \| `"fetchPreviousPage"` \| `"hasNextPage"` \| `"hasPreviousPage"` \| `"isFetchNextPageError"` \| `"isFetchingNextPage"` \| `"isFetchPreviousPageError"` \| `"isFetchingPreviousPage"`)[] \| `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. |
441| <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. |
442| <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. |
443| <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`. |
444| <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. |
445| <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`). |
446| <a id="options-property-querykeyhashfn"></a> `queryKeyHashFn?` | (`queryKey`: `TQueryKey`) => `string` | `undefined` | If specified, this function is used to hash the `queryKey` to a string. |
447| <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 |
448| <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. |
449| <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 |
450| <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'`. |
451| <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. |
452| <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. |
453| <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. |
454| <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. |
455| <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. |
456| <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`. |
457| <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. |
458| <a id="options-property-subscribed"></a> `subscribed?` | `boolean` | `true` | Set this to `false` to unsubscribe this observer from updates to the query cache. |
459| <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`). |
460β
461### queryClient?
462β
463[`QueryClient`](../classes/QueryClient.md)
464β
465Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
466be used.
467β
468<a id="returns-summary"></a>
469β
470## Returns
471β
472[`UseQueryResult`](../type-aliases/UseQueryResult.md)\<`TData`, `TError`\>
473β
474The current query result. `status` is `pending` if there is no cached data to display, `error` if
475the last fetch attempt failed, or `success` if the query has data to display. `isPending`/`isSuccess`/`isError`
476are derived booleans for convenience.
477β
478<a id="result-properties"></a>
479β
480### Result properties
481β
482| Property | Type | Description |
483| ------ | ------ | ------ |
484| <a id="result-property-data"></a> `data` | `TData` \| `undefined` | The last successfully resolved data for the query. |
485| <a id="result-property-dataupdatedat"></a> `dataUpdatedAt` | `number` | The timestamp for when the query most recently returned the `status` as `"success"`. |
486| <a id="result-property-error"></a> `error` | `TError` \| `null` | The error object for the query, if an error was thrown. - Defaults to `null`. |
487| <a id="result-property-errorupdatecount"></a> `errorUpdateCount` | `number` | The sum of all errors. |
488| <a id="result-property-errorupdatedat"></a> `errorUpdatedAt` | `number` | The timestamp for when the query most recently returned the `status` as `"error"`. |
489| <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. |
490| <a id="result-property-failurereason"></a> `failureReason` | `TError` \| `null` | The failure reason for the query retry. - Reset to `null` when the query succeeds. |
491| <a id="result-property-fetchstatus"></a> `fetchStatus` | `"fetching"` \| `"paused"` \| `"idle"` | 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. |
492| <a id="result-property-isenabled"></a> `isEnabled` | `boolean` | `true` if this observer is enabled, `false` otherwise. |
493| <a id="result-property-iserror"></a> `isError` | `boolean` | A derived boolean from the `status` variable, provided for convenience. - `true` if the query attempt resulted in an error. |
494| <a id="result-property-isfetched"></a> `isFetched` | `boolean` | Will be `true` if the query has been fetched. |
495| <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. |
496| <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. |
497| <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. |
498| <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`. |
499| <a id="result-property-isloadingerror"></a> `isLoadingError` | `boolean` | Will be `true` if the query failed while fetching for the first time. |
500| <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`. |
501| <a id="result-property-ispending"></a> `isPending` | `boolean` | Will be `pending` if there's no cached data and no query attempt was finished yet. |
502| <a id="result-property-isplaceholderdata"></a> `isPlaceholderData` | `boolean` | Will be `true` if the data shown is the placeholder data. |
503| <a id="result-property-isrefetcherror"></a> `isRefetchError` | `boolean` | Will be `true` if the query failed while refetching. |
504| <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`. |
505| <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`. |
506| <a id="result-property-issuccess"></a> `isSuccess` | `boolean` | A derived boolean from the `status` variable, provided for convenience. - `true` if the query has received a response with no errors and is ready to display its data. |
507| <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. |
508| <a id="result-property-status"></a> `status` | `"error"` \| `"pending"` \| `"success"` | The status of the query. - Will be: - `pending` if there's no cached data and no query attempt was finished yet. - `error` if the query attempt resulted in an error. - `success` if the query has received a response with no errors and is ready to display its data. |