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

useQuery.md

506 lines31.7 KB

1---
2id: useQuery
3title: useQuery
4---
5​
6<!-- DO NOT EDIT: this page is autogenerated from the type comments -->
7​
8## Overview
9​
10```ts
11function useQuery<TQueryFnData = unknown, TError = Error, TData = TQueryFnData, TQueryKey extends readonly unknown[] = readonly unknown[]>(options: DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>, queryClient?: QueryClient): DefinedUseQueryResult<TData, TError>;
12function useQuery<TQueryFnData = unknown, TError = Error, TData = TQueryFnData, TQueryKey extends readonly unknown[] = readonly unknown[]>(options: UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>, queryClient?: QueryClient): UseQueryResult<TData, TError>;
13function useQuery<TQueryFnData = unknown, TError = Error, TData = TQueryFnData, TQueryKey extends readonly unknown[] = readonly unknown[]>(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 known to be defined, 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, may be `undefined`, or is a function that may return `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 = unknown, TError = Error, TData = TQueryFnData, TQueryKey extends readonly unknown[] = readonly unknown[]>(options: DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>, queryClient?: QueryClient): DefinedUseQueryResult<TData, TError>;
28```
29​
30Defined in: [packages/preact-query/src/useQuery.ts:49](https://github.com/TanStack/query/blob/main/packages/preact-query/src/useQuery.ts#L49)
31​
32This overload is selected when `initialData` is known to be defined, so the resulting `data` is never
33`undefined` (unless a `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` known to be defined.
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/preact-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 )
103```
104​
105<a id="call-signature-2"></a>
106​
107## Call Signature
108​
109```ts
110function useQuery<TQueryFnData = unknown, TError = Error, TData = TQueryFnData, TQueryKey extends readonly unknown[] = readonly unknown[]>(options: UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>, queryClient?: QueryClient): UseQueryResult<TData, TError>;
111```
112​
113Defined in: [packages/preact-query/src/useQuery.ts:116](https://github.com/TanStack/query/blob/main/packages/preact-query/src/useQuery.ts#L116)
114​
115This overload is selected when `initialData` is omitted, may be `undefined`, or is a function that may
116return `undefined`, so the resulting `data` can 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/preact-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 )
188```
189​
190The same query, checking `isPending`/`isError` instead of `status` β€” pick whichever reads better to you:
191```tsx
192import { useQuery } from '@tanstack/preact-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 )
209```
210​
211<a id="call-signature-3"></a>
212​
213## Call Signature
214​
215```ts
216function useQuery<TQueryFnData = unknown, TError = Error, TData = TQueryFnData, TQueryKey extends readonly unknown[] = readonly unknown[]>(options: UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>, queryClient?: QueryClient): UseQueryResult<TData, TError>;
217```
218​
219Defined in: [packages/preact-query/src/useQuery.ts:281](https://github.com/TanStack/query/blob/main/packages/preact-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/preact-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 )
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/preact-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>
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/preact-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>
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/preact-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>
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/preact-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>
381```
382​
383Paginated data, keeping the previous page's data visible while the next page loads:
384```tsx
385import { keepPreviousData, useQuery } from '@tanstack/preact-query'
386import { useState } from 'preact/hooks'
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 )
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. |