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