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