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 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 )
106}
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 )
192}
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 )
213}
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 )
300}
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>
319}
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>
339}
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>
360}
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>
386}
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 )
418}
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. |