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