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

useInfiniteQuery.md

578 lines38.7 KB

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 known to be defined.
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` known to be defined.
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 )
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 )
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 )
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 )
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 )
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 )
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?` | \| `"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. |
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` | `"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. |
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 has an error from a fetch that failed after its retries, or if `select` threw. |
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 has an error and no data to display. |
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 `true` if the query has no cached data, no data from `placeholderData` and no error. |
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 has an error and still has data to display (for infinite queries, not after a failed page fetch). |
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 cached data or data from `placeholderData`, and no error. |
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: - `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. |