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

useInfiniteQuery.md

576 lines37.8 KB

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