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

useQuery.md

504 lines31.1 KB

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