Open History to see the last commit
1---
2id: useInfiniteQuery
3title: useInfiniteQuery
4---
5β
6## Overview
7β
8```ts
9function useInfiniteQuery<TQueryFnData, TError, TData, TQueryKey, TPageParam>(options: DefinedInitialDataInfiniteOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>, queryClient?: QueryClient): DefinedUseInfiniteQueryResult<TData, TError>;
10function useInfiniteQuery<TQueryFnData, TError, TData, TQueryKey, TPageParam>(options: UndefinedInitialDataInfiniteOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>, queryClient?: QueryClient): UseInfiniteQueryResult<TData, TError>;
11function useInfiniteQuery<TQueryFnData, TError, TData, TQueryKey, TPageParam>(options: UseInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>, queryClient?: QueryClient): UseInfiniteQueryResult<TData, TError>;
12```
13β
14- [`DefinedInitialDataInfiniteOptions` β `DefinedUseInfiniteQueryResult`](#call-signature-1): The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of `initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`.
15- [`UndefinedInitialDataInfiniteOptions` β `UseInfiniteQueryResult`](#call-signature-2): The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of `initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`.
16- [`UseInfiniteQueryOptions` β `UseInfiniteQueryResult`](#call-signature-3): The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of `initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`.
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 useInfiniteQuery<TQueryFnData, TError, TData, TQueryKey, TPageParam>(options: DefinedInitialDataInfiniteOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>, queryClient?: QueryClient): DefinedUseInfiniteQueryResult<TData, TError>;
26```
27β
28Defined in: [packages/preact-query/src/useInfiniteQuery.ts:63](https://github.com/TanStack/query/blob/main/packages/preact-query/src/useInfiniteQuery.ts#L63)
29β
30The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of
31`initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`.
32β
33This overload is selected when `initialData` is set.
34β
35### Type Parameters
36β
37#### TQueryFnData
38β
39`TQueryFnData`
40β
41#### TError
42β
43`TError` = `Error`
44β
45#### TData
46β
47`TData` = [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `unknown`\>
48β
49#### TQueryKey
50β
51`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
52β
53#### TPageParam
54β
55`TPageParam` = `unknown`
56β
57### Parameters
58β
59#### options
60β
61[`DefinedInitialDataInfiniteOptions`](../type-aliases/DefinedInitialDataInfiniteOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\>
62β
63The [DefinedInitialDataInfiniteOptions](../type-aliases/DefinedInitialDataInfiniteOptions.md) to use β everything you can pass to `useInfiniteQuery`, with `initialData` set.
64β
65#### queryClient?
66β
67[`QueryClient`](../classes/QueryClient.md)
68β
69Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
70be used.
71β
72### Returns
73β
74[`DefinedUseInfiniteQueryResult`](../type-aliases/DefinedUseInfiniteQueryResult.md)\<`TData`, `TError`\>
75β
76The same properties as `useQuery`, with the addition of `fetchNextPage`, `fetchPreviousPage`,
77`hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and `isFetchingPreviousPage`. `data.pages` and
78`data.pageParams` are also added, as long as a `select` doesn't change `TData` away from its default
79`InfiniteData<TQueryFnData>` shape.
80β
81### Remarks
82β
83Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default
84refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user
85actions, or add conditions like `hasNextPage && !isFetching`.
86β
87### See
88β
89[infiniteQueryOptions](infiniteQueryOptions.md) to share these options between `useInfiniteQuery` and imperative APIs like `queryClient.infiniteQuery`.
90β
91### Example
92β
93```tsx
94import { useInfiniteQuery } from '@tanstack/preact-query'
95β
96function Projects() {
97 // `data` is never `undefined`, thanks to `initialData` β even if a refetch fails, so the
98 // list stays visible alongside the error.
99 const { data, isError, error } = useInfiniteQuery({
100 queryKey: ['projects'],
101 queryFn: ({ pageParam }) => fetchProjects(pageParam),
102 initialPageParam: 0,
103 getNextPageParam: (lastPage) => lastPage.nextId,
104 initialData: { pages: [], pageParams: [] },
105 })
106β
107 return (
108 <div>
109 {isError ? <span>Error: {error.message}</span> : null}
110 <ul>
111 {data.pages.map((page) => page.projects.map((p) => <li key={p.id}>{p.name}</li>))}
112 </ul>
113 </div>
114 )
115}
116```
117β
118<a id="call-signature-2"></a>
119β
120## Call Signature
121β
122```ts
123function useInfiniteQuery<TQueryFnData, TError, TData, TQueryKey, TPageParam>(options: UndefinedInitialDataInfiniteOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>, queryClient?: QueryClient): UseInfiniteQueryResult<TData, TError>;
124```
125β
126Defined in: [packages/preact-query/src/useInfiniteQuery.ts:186](https://github.com/TanStack/query/blob/main/packages/preact-query/src/useInfiniteQuery.ts#L186)
127β
128The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of
129`initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`.
130β
131### Type Parameters
132β
133#### TQueryFnData
134β
135`TQueryFnData`
136β
137#### TError
138β
139`TError` = `Error`
140β
141#### TData
142β
143`TData` = [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `unknown`\>
144β
145#### TQueryKey
146β
147`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
148β
149#### TPageParam
150β
151`TPageParam` = `unknown`
152β
153### Parameters
154β
155#### options
156β
157[`UndefinedInitialDataInfiniteOptions`](../type-aliases/UndefinedInitialDataInfiniteOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\>
158β
159The [UndefinedInitialDataInfiniteOptions](../type-aliases/UndefinedInitialDataInfiniteOptions.md) to use β everything you can pass to `useInfiniteQuery`.
160β
161#### queryClient?
162β
163[`QueryClient`](../classes/QueryClient.md)
164β
165Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
166be used.
167β
168### Returns
169β
170[`UseInfiniteQueryResult`](../type-aliases/UseInfiniteQueryResult.md)\<`TData`, `TError`\>
171β
172The same properties as `useQuery`, with the addition of `fetchNextPage`, `fetchPreviousPage`,
173`hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and `isFetchingPreviousPage`. `data.pages` and
174`data.pageParams` are also added, as long as a `select` doesn't change `TData` away from its default
175`InfiniteData<TQueryFnData>` shape.
176β
177### Remarks
178β
179Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default
180refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user
181actions, or add conditions like `hasNextPage && !isFetching`.
182β
183### See
184β
185[infiniteQueryOptions](infiniteQueryOptions.md) to share these options between `useInfiniteQuery` and imperative APIs like `queryClient.infiniteQuery`.
186β
187### Examples
188β
189Fetching the next page from a "Load More" button click:
190```tsx
191import { useInfiniteQuery } from '@tanstack/preact-query'
192β
193function Projects() {
194 const { data, isPending, isError, error, fetchNextPage, hasNextPage, isFetching, isFetchingNextPage } =
195 useInfiniteQuery({
196 queryKey: ['projects'],
197 queryFn: ({ pageParam }) => fetchProjects(pageParam),
198 initialPageParam: 0,
199 getNextPageParam: (lastPage) => lastPage.nextId,
200 })
201β
202 if (isPending) return 'Loading...'
203 if (isError) return <span>Error: {error.message}</span>
204β
205 return (
206 <>
207 <ul>
208 {data.pages.map((page) =>
209 page.projects.map((project) => <li key={project.id}>{project.name}</li>),
210 )}
211 </ul>
212 <button
213 onClick={() => fetchNextPage()}
214 disabled={!hasNextPage || isFetching}
215 >
216 {isFetchingNextPage
217 ? 'Loading more...'
218 : hasNextPage
219 ? 'Load More'
220 : 'Nothing more to load'}
221 </button>
222 </>
223 )
224}
225```
226β
227Fetching the next page automatically as the user scrolls, using an `IntersectionObserver` on a
228sentinel element after the list:
229```tsx
230import { useInfiniteQuery } from '@tanstack/preact-query'
231import { useEffect, useRef } from 'preact/hooks'
232β
233function Projects() {
234 const {
235 data,
236 isPending,
237 isError,
238 error,
239 fetchNextPage,
240 hasNextPage,
241 isFetching,
242 isFetchingNextPage,
243 } = useInfiniteQuery({
244 queryKey: ['projects'],
245 queryFn: ({ pageParam }) => fetchProjects(pageParam),
246 initialPageParam: 0,
247 getNextPageParam: (lastPage) => lastPage.nextId,
248 })
249β
250 const sentinelRef = useRef<HTMLDivElement>(null)
251β
252 useEffect(() => {
253 const sentinel = sentinelRef.current
254 if (sentinel == null || !hasNextPage || isFetching) return
255β
256 const observer = new IntersectionObserver(([entry]) => {
257 if (entry?.isIntersecting) fetchNextPage()
258 })
259 observer.observe(sentinel)
260β
261 return () => observer.disconnect()
262 }, [hasNextPage, isFetching, fetchNextPage])
263β
264 if (isPending) return 'Loading...'
265 if (isError) return <span>Error: {error.message}</span>
266β
267 return (
268 <>
269 <ul>
270 {data.pages.map((page) =>
271 page.projects.map((project) => <li key={project.id}>{project.name}</li>),
272 )}
273 </ul>
274 <div ref={sentinelRef}>{isFetchingNextPage ? 'Loading more...' : null}</div>
275 </>
276 )
277}
278```
279β
280<a id="call-signature-3"></a>
281β
282## Call Signature
283β
284```ts
285function useInfiniteQuery<TQueryFnData, TError, TData, TQueryKey, TPageParam>(options: UseInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>, queryClient?: QueryClient): UseInfiniteQueryResult<TData, TError>;
286```
287β
288Defined in: [packages/preact-query/src/useInfiniteQuery.ts:338](https://github.com/TanStack/query/blob/main/packages/preact-query/src/useInfiniteQuery.ts#L338)
289β
290The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of
291`initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`.
292β
293### Type Parameters
294β
295#### TQueryFnData
296β
297`TQueryFnData`
298β
299#### TError
300β
301`TError` = `Error`
302β
303#### TData
304β
305`TData` = [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `unknown`\>
306β
307#### TQueryKey
308β
309`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
310β
311#### TPageParam
312β
313`TPageParam` = `unknown`
314β
315### Parameters
316β
317#### options
318β
319[`UseInfiniteQueryOptions`](../interfaces/UseInfiniteQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\>
320β
321The [UseInfiniteQueryOptions](../interfaces/UseInfiniteQueryOptions.md) to use β everything you can pass to `useInfiniteQuery`.
322β
323#### queryClient?
324β
325[`QueryClient`](../classes/QueryClient.md)
326β
327Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
328be used.
329β
330### Returns
331β
332[`UseInfiniteQueryResult`](../type-aliases/UseInfiniteQueryResult.md)\<`TData`, `TError`\>
333β
334The same properties as `useQuery`, with the addition of `fetchNextPage`, `fetchPreviousPage`,
335`hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and `isFetchingPreviousPage`. `data.pages` and
336`data.pageParams` are also added, as long as a `select` doesn't change `TData` away from its default
337`InfiniteData<TQueryFnData>` shape.
338β
339### Remarks
340β
341Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default
342refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user
343actions, or add conditions like `hasNextPage && !isFetching`.
344β
345### See
346β
347[infiniteQueryOptions](infiniteQueryOptions.md) to share these options between `useInfiniteQuery` and imperative APIs like `queryClient.infiniteQuery`.
348β
349### Examples
350β
351Fetching the next page from a "Load More" button click:
352```tsx
353import { useInfiniteQuery } from '@tanstack/preact-query'
354β
355function Projects() {
356 const { data, isPending, isError, error, fetchNextPage, hasNextPage, isFetching, isFetchingNextPage } =
357 useInfiniteQuery({
358 queryKey: ['projects'],
359 queryFn: ({ pageParam }) => fetchProjects(pageParam),
360 initialPageParam: 0,
361 getNextPageParam: (lastPage) => lastPage.nextId,
362 })
363β
364 if (isPending) return 'Loading...'
365 if (isError) return <span>Error: {error.message}</span>
366β
367 return (
368 <>
369 <ul>
370 {data.pages.map((page) =>
371 page.projects.map((project) => <li key={project.id}>{project.name}</li>),
372 )}
373 </ul>
374 <button
375 onClick={() => fetchNextPage()}
376 disabled={!hasNextPage || isFetching}
377 >
378 {isFetchingNextPage
379 ? 'Loading more...'
380 : hasNextPage
381 ? 'Load More'
382 : 'Nothing more to load'}
383 </button>
384 </>
385 )
386}
387```
388β
389Fetching the next page automatically as the user scrolls, using an `IntersectionObserver` on a
390sentinel element after the list:
391```tsx
392import { useInfiniteQuery } from '@tanstack/preact-query'
393import { useEffect, useRef } from 'preact/hooks'
394β
395function Projects() {
396 const {
397 data,
398 isPending,
399 isError,
400 error,
401 fetchNextPage,
402 hasNextPage,
403 isFetching,
404 isFetchingNextPage,
405 } = useInfiniteQuery({
406 queryKey: ['projects'],
407 queryFn: ({ pageParam }) => fetchProjects(pageParam),
408 initialPageParam: 0,
409 getNextPageParam: (lastPage) => lastPage.nextId,
410 })
411β
412 const sentinelRef = useRef<HTMLDivElement>(null)
413β
414 useEffect(() => {
415 const sentinel = sentinelRef.current
416 if (sentinel == null || !hasNextPage || isFetching) return
417β
418 const observer = new IntersectionObserver(([entry]) => {
419 if (entry?.isIntersecting) fetchNextPage()
420 })
421 observer.observe(sentinel)
422β
423 return () => observer.disconnect()
424 }, [hasNextPage, isFetching, fetchNextPage])
425β
426 if (isPending) return 'Loading...'
427 if (isError) return <span>Error: {error.message}</span>
428β
429 return (
430 <>
431 <ul>
432 {data.pages.map((page) =>
433 page.projects.map((project) => <li key={project.id}>{project.name}</li>),
434 )}
435 </ul>
436 <div ref={sentinelRef}>{isFetchingNextPage ? 'Loading more...' : null}</div>
437 </>
438 )
439}
440```
441β
442A query that's disabled, type safe, until `postId` is set β pass `skipToken` as `queryFn`
443instead of setting `enabled: false`:
444```tsx
445import { skipToken, useInfiniteQuery } from '@tanstack/preact-query'
446β
447function Comments({ postId }: { postId: string | undefined }) {
448 // Use `isLoading`, not `isPending`, so the loading state doesn't show while the query is disabled.
449 const { data, isLoading, isError, error } = useInfiniteQuery({
450 queryKey: ['post', postId, 'comments'],
451 queryFn:
452 postId != null
453 ? ({ pageParam }) => fetchComments(postId, pageParam)
454 : skipToken,
455 initialPageParam: 0,
456 getNextPageParam: (lastPage) => lastPage.nextId,
457 })
458β
459 if (postId == null) return 'Select a post'
460 if (isLoading) return 'Loading...'
461 if (isError) return <span>Error: {error.message}</span>
462β
463 return (
464 <ul>
465 {data?.pages.map((page) => page.comments.map((c) => <li key={c.id}>{c.text}</li>))}
466 </ul>
467 )
468}
469```
470β
471<a id="parameters-summary"></a>
472β
473## Parameters
474β
475### options
476β
477[`UseInfiniteQueryOptions`](../interfaces/UseInfiniteQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\>
478β
479The [UseInfiniteQueryOptions](../interfaces/UseInfiniteQueryOptions.md) to use β everything you can pass to `useInfiniteQuery`.
480β
481<a id="options-properties"></a>
482β
483#### `options` properties
484β
485| Property | Type | Default value | Description |
486| ------ | ------ | ------ | ------ |
487| <a id="options-property-enabled"></a> `enabled?` | \| `false` \| `true` \| ((`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `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. |
488| <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. |
489| <a id="options-property-getnextpageparam"></a> `getNextPageParam` | (`lastPage`: `TQueryFnData`, `allPages`: `TQueryFnData`[], `lastPageParam`: `TPageParam`, `allPageParams`: `TPageParam`[]) => `TPageParam` \| `null` \| `undefined` | `undefined` | This function can be set to automatically get the next cursor for infinite queries. The result will also be used to determine the value of `hasNextPage`. |
490| <a id="options-property-getpreviouspageparam"></a> `getPreviousPageParam?` | (`firstPage`: `TQueryFnData`, `allPages`: `TQueryFnData`[], `firstPageParam`: `TPageParam`, `allPageParams`: `TPageParam`[]) => `TPageParam` \| `null` \| `undefined` | `undefined` | This function can be set to automatically get the previous cursor for infinite queries. The result will also be used to determine the value of `hasPreviousPage`. |
491| <a id="options-property-initialdata"></a> `initialData?` | \| [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\> \| (() => \| [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\> \| `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. |
492| <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. |
493| <a id="options-property-initialpageparam"></a> `initialPageParam` | `TPageParam` | `undefined` | The page param to start from when an infinite query has no pages yet. It is passed to `queryFn` as `pageParam` for the first page; every page after that gets the value returned by `getNextPageParam` or `getPreviousPageParam`. It only applies while the query has no pages: once a first page exists, refetching starts from that page's own param instead. |
494| <a id="options-property-maxpages"></a> `maxPages?` | `number` | `undefined` | Maximum number of pages to store in the data of an infinite query. |
495| <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. |
496| <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. |
497| <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. |
498| <a id="options-property-persister"></a> `persister?` | (`queryFn`: (`context`: [`QueryFunctionContext`](../type-aliases/QueryFunctionContext.md)\<`NoInfer`\<`TQueryKey`\>, `TPageParam`\>) => `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. |
499| <a id="options-property-placeholderdata"></a> `placeholderData?` | \| [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\> \| ((`previousData`: \| [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\> \| `undefined`, `previousQuery`: \| [`Query`](../classes/Query.md)\<[`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\> \| `undefined`) => \| [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\> \| `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. |
500| <a id="options-property-queryfn"></a> `queryFn?` | \| *typeof* [`skipToken`](../variables/skipToken.md) \| ((`context`: [`QueryFunctionContext`](../type-aliases/QueryFunctionContext.md)\<`TQueryKey`, `TPageParam`\>) => `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`. |
501| <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. |
502| <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`). |
503| <a id="options-property-querykeyhashfn"></a> `queryKeyHashFn?` | (`queryKey`: `TQueryKey`) => `string` | `undefined` | If specified, this function is used to hash the `queryKey` to a string. |
504| <a id="options-property-refetchinterval"></a> `refetchInterval?` | \| `number` \| `false` \| ((`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `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 |
505| <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. |
506| <a id="options-property-refetchonmount"></a> `refetchOnMount?` | \| `boolean` \| `"always"` \| ((`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `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 |
507| <a id="options-property-refetchonreconnect"></a> `refetchOnReconnect?` | \| `boolean` \| `"always"` \| ((`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `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'`. |
508| <a id="options-property-refetchonwindowfocus"></a> `refetchOnWindowFocus?` | \| `boolean` \| `"always"` \| ((`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `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. |
509| <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. |
510| <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. |
511| <a id="options-property-retryonmount"></a> `retryOnMount?` | \| `false` \| `true` \| ((`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `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. |
512| <a id="options-property-select"></a> `select?` | (`data`: [`InfiniteData`](../interfaces/InfiniteData.md)) => `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. |
513| <a id="options-property-staletime"></a> `staleTime?` | \| `number` \| `"static"` \| ((`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `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`. |
514| <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. |
515| <a id="options-property-subscribed"></a> `subscribed?` | `boolean` | `true` | Set this to `false` to unsubscribe this observer from updates to the query cache. |
516| <a id="options-property-throwonerror"></a> `throwOnError?` | \| `false` \| `true` \| ((`error`: `TError`, `query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `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`). |
517β
518### queryClient?
519β
520[`QueryClient`](../classes/QueryClient.md)
521β
522Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
523be used.
524β
525<a id="returns-summary"></a>
526β
527## Returns
528β
529[`UseInfiniteQueryResult`](../type-aliases/UseInfiniteQueryResult.md)\<`TData`, `TError`\>
530β
531The same properties as `useQuery`, with the addition of `fetchNextPage`, `fetchPreviousPage`,
532`hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and `isFetchingPreviousPage`. `data.pages` and
533`data.pageParams` are also added, as long as a `select` doesn't change `TData` away from its default
534`InfiniteData<TQueryFnData>` shape.
535β
536<a id="result-properties"></a>
537β
538### Result properties
539β
540| Property | Type | Description |
541| ------ | ------ | ------ |
542| <a id="result-property-data"></a> `data` | `TData` \| `undefined` | The last successfully resolved data for the query. |
543| <a id="result-property-dataupdatedat"></a> `dataUpdatedAt` | `number` | The timestamp for when the query most recently returned the `status` as `"success"`. |
544| <a id="result-property-error"></a> `error` | `TError` \| `null` | The error object for the query, if an error was thrown. - Defaults to `null`. |
545| <a id="result-property-errorupdatecount"></a> `errorUpdateCount` | `number` | The sum of all errors. |
546| <a id="result-property-errorupdatedat"></a> `errorUpdatedAt` | `number` | The timestamp for when the query most recently returned the `status` as `"error"`. |
547| <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. |
548| <a id="result-property-failurereason"></a> `failureReason` | `TError` \| `null` | The failure reason for the query retry. - Reset to `null` when the query succeeds. |
549| <a id="result-property-fetchnextpage"></a> `fetchNextPage` | (`options?`: [`FetchNextPageOptions`](../interfaces/FetchNextPageOptions.md)) => `Promise`\<[`InfiniteQueryObserverResult`](../type-aliases/InfiniteQueryObserverResult.md)\<`TData`, `TError`\>\> | This function allows you to fetch the next "page" of results. |
550| <a id="result-property-fetchpreviouspage"></a> `fetchPreviousPage` | (`options?`: [`FetchPreviousPageOptions`](../interfaces/FetchPreviousPageOptions.md)) => `Promise`\<[`InfiniteQueryObserverResult`](../type-aliases/InfiniteQueryObserverResult.md)\<`TData`, `TError`\>\> | This function allows you to fetch the previous "page" of results. |
551| <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. |
552| <a id="result-property-hasnextpage"></a> `hasNextPage` | `boolean` | Will be `true` if there is a next page to be fetched (known via the `getNextPageParam` option). |
553| <a id="result-property-haspreviouspage"></a> `hasPreviousPage` | `boolean` | Will be `true` if there is a previous page to be fetched (known via the `getPreviousPageParam` option). |
554| <a id="result-property-isenabled"></a> `isEnabled` | `boolean` | `true` if this observer is enabled, `false` otherwise. |
555| <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. |
556| <a id="result-property-isfetched"></a> `isFetched` | `boolean` | Will be `true` if the query has been fetched. |
557| <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. |
558| <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. |
559| <a id="result-property-isfetchingnextpage"></a> `isFetchingNextPage` | `boolean` | Will be `true` while fetching the next page with `fetchNextPage`. |
560| <a id="result-property-isfetchingpreviouspage"></a> `isFetchingPreviousPage` | `boolean` | Will be `true` while fetching the previous page with `fetchPreviousPage`. |
561| <a id="result-property-isfetchnextpageerror"></a> `isFetchNextPageError` | `boolean` | Will be `true` if the query failed while fetching the next page. |
562| <a id="result-property-isfetchpreviouspageerror"></a> `isFetchPreviousPageError` | `boolean` | Will be `true` if the query failed while fetching the previous page. |
563| <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. |
564| <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`. |
565| <a id="result-property-isloadingerror"></a> `isLoadingError` | `boolean` | Will be `true` if the query failed while fetching for the first time. |
566| <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`. |
567| <a id="result-property-ispending"></a> `isPending` | `boolean` | Will be `pending` if there's no cached data and no query attempt was finished yet. |
568| <a id="result-property-isplaceholderdata"></a> `isPlaceholderData` | `boolean` | Will be `true` if the data shown is the placeholder data. |
569| <a id="result-property-isrefetcherror"></a> `isRefetchError` | `boolean` | Will be `true` if the query failed while refetching. |
570| <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`. |
571| <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`. |
572| <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. |
573| <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. |
574| <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. |