Open History to see the last commit
1---
2id: useInfiniteQuery
3title: useInfiniteQuery
4redirect_from:
5 - framework/react/reference/useInfiniteQuery
6---
7β
8## Call Signature
9β
10```ts
11function useInfiniteQuery<TQueryFnData, TError, TData, TQueryKey, TPageParam>(options: DefinedInitialDataInfiniteOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>, queryClient?: QueryClient): DefinedUseInfiniteQueryResult<TData, TError>;
12```
13β
14Defined in: [packages/react-query/src/useInfiniteQuery.ts:65](https://github.com/TanStack/query/blob/main/packages/react-query/src/useInfiniteQuery.ts#L65)
15β
16The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of
17`initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`.
18β
19This overload is selected when `initialData` is set.
20β
21### Type Parameters
22β
23#### TQueryFnData
24β
25`TQueryFnData`
26β
27#### TError
28β
29`TError` = `Error`
30β
31#### TData
32β
33`TData` = [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `unknown`\>
34β
35#### TQueryKey
36β
37`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
38β
39#### TPageParam
40β
41`TPageParam` = `unknown`
42β
43### Parameters
44β
45#### options
46β
47[`DefinedInitialDataInfiniteOptions`](../type-aliases/DefinedInitialDataInfiniteOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\>
48β
49The [DefinedInitialDataInfiniteOptions](../type-aliases/DefinedInitialDataInfiniteOptions.md) to use β everything you can pass to `useInfiniteQuery`, with `initialData` set.
50β
51#### queryClient?
52β
53[`QueryClient`](../classes/QueryClient.md)
54β
55Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
56be used.
57β
58### Returns
59β
60[`DefinedUseInfiniteQueryResult`](../type-aliases/DefinedUseInfiniteQueryResult.md)\<`TData`, `TError`\>
61β
62The same properties as `useQuery`, with the addition of `fetchNextPage`, `fetchPreviousPage`,
63`hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and `isFetchingPreviousPage`. `data.pages` and
64`data.pageParams` are also added, as long as a `select` doesn't change `TData` away from its default
65`InfiniteData<TQueryFnData>` shape.
66β
67### Remarks
68β
69Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default
70refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user
71actions, or add conditions like `hasNextPage && !isFetching`.
72β
73### See
74β
75[infiniteQueryOptions](infiniteQueryOptions.md) to share these options between `useInfiniteQuery` and imperative APIs like `queryClient.infiniteQuery`.
76β
77### Example
78β
79```tsx
80import { useInfiniteQuery } from '@tanstack/react-query'
81β
82function Projects() {
83 // `data` is never `undefined`, thanks to `initialData` β even if a refetch fails, so the
84 // list stays visible alongside the error.
85 const { data, isError, error } = useInfiniteQuery({
86 queryKey: ['projects'],
87 queryFn: ({ pageParam }) => fetchProjects(pageParam),
88 initialPageParam: 0,
89 getNextPageParam: (lastPage) => lastPage.nextId,
90 initialData: { pages: [], pageParams: [] },
91 })
92β
93 return (
94 <div>
95 {isError ? <span>Error: {error.message}</span> : null}
96 <ul>
97 {data.pages.map((page) => page.projects.map((p) => <li key={p.id}>{p.name}</li>))}
98 </ul>
99 </div>
100 )
101}
102```
103β
104## Call Signature
105β
106```ts
107function useInfiniteQuery<TQueryFnData, TError, TData, TQueryKey, TPageParam>(options: UndefinedInitialDataInfiniteOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>, queryClient?: QueryClient): UseInfiniteQueryResult<TData, TError>;
108```
109β
110Defined in: [packages/react-query/src/useInfiniteQuery.ts:191](https://github.com/TanStack/query/blob/main/packages/react-query/src/useInfiniteQuery.ts#L191)
111β
112The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of
113`initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`.
114β
115### Type Parameters
116β
117#### TQueryFnData
118β
119`TQueryFnData`
120β
121#### TError
122β
123`TError` = `Error`
124β
125#### TData
126β
127`TData` = [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `unknown`\>
128β
129#### TQueryKey
130β
131`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
132β
133#### TPageParam
134β
135`TPageParam` = `unknown`
136β
137### Parameters
138β
139#### options
140β
141[`UndefinedInitialDataInfiniteOptions`](../type-aliases/UndefinedInitialDataInfiniteOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\>
142β
143The [UndefinedInitialDataInfiniteOptions](../type-aliases/UndefinedInitialDataInfiniteOptions.md) to use β everything you can pass to `useInfiniteQuery`.
144β
145#### queryClient?
146β
147[`QueryClient`](../classes/QueryClient.md)
148β
149Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
150be used.
151β
152### Returns
153β
154[`UseInfiniteQueryResult`](../type-aliases/UseInfiniteQueryResult.md)\<`TData`, `TError`\>
155β
156The same properties as `useQuery`, with the addition of `fetchNextPage`, `fetchPreviousPage`,
157`hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and `isFetchingPreviousPage`. `data.pages` and
158`data.pageParams` are also added, as long as a `select` doesn't change `TData` away from its default
159`InfiniteData<TQueryFnData>` shape.
160β
161### Remarks
162β
163Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default
164refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user
165actions, or add conditions like `hasNextPage && !isFetching`.
166β
167### See
168β
169[infiniteQueryOptions](infiniteQueryOptions.md) to share these options between `useInfiniteQuery` and imperative APIs like `queryClient.infiniteQuery`.
170β
171### Examples
172β
173Fetching the next page from a "Load More" button click:
174```tsx
175import { useInfiniteQuery } from '@tanstack/react-query'
176β
177function Projects() {
178 const { data, isPending, isError, error, fetchNextPage, hasNextPage, isFetching, isFetchingNextPage } =
179 useInfiniteQuery({
180 queryKey: ['projects'],
181 queryFn: ({ pageParam }) => fetchProjects(pageParam),
182 initialPageParam: 0,
183 getNextPageParam: (lastPage) => lastPage.nextId,
184 })
185β
186 if (isPending) return 'Loading...'
187 if (isError) return <span>Error: {error.message}</span>
188β
189 return (
190 <>
191 <ul>
192 {data.pages.map((page) =>
193 page.projects.map((project) => <li key={project.id}>{project.name}</li>),
194 )}
195 </ul>
196 <button
197 onClick={() => fetchNextPage()}
198 disabled={!hasNextPage || isFetching}
199 >
200 {isFetchingNextPage
201 ? 'Loading more...'
202 : hasNextPage
203 ? 'Load More'
204 : 'Nothing more to load'}
205 </button>
206 </>
207 )
208}
209```
210β
211Fetching the next page automatically as the user scrolls, using an `IntersectionObserver` on a
212sentinel element after the list:
213```tsx
214import { useInfiniteQuery } from '@tanstack/react-query'
215import { useEffect, useRef } from 'react'
216β
217function Projects() {
218 const {
219 data,
220 isPending,
221 isError,
222 error,
223 fetchNextPage,
224 hasNextPage,
225 isFetching,
226 isFetchingNextPage,
227 } = useInfiniteQuery({
228 queryKey: ['projects'],
229 queryFn: ({ pageParam }) => fetchProjects(pageParam),
230 initialPageParam: 0,
231 getNextPageParam: (lastPage) => lastPage.nextId,
232 })
233β
234 const sentinelRef = useRef<HTMLDivElement>(null)
235β
236 useEffect(() => {
237 const sentinel = sentinelRef.current
238 if (sentinel == null || !hasNextPage || isFetching) return
239β
240 const observer = new IntersectionObserver(([entry]) => {
241 if (entry?.isIntersecting) fetchNextPage()
242 })
243 observer.observe(sentinel)
244β
245 return () => observer.disconnect()
246 }, [hasNextPage, isFetching, fetchNextPage])
247β
248 if (isPending) return 'Loading...'
249 if (isError) return <span>Error: {error.message}</span>
250β
251 return (
252 <>
253 <ul>
254 {data.pages.map((page) =>
255 page.projects.map((project) => <li key={project.id}>{project.name}</li>),
256 )}
257 </ul>
258 <div ref={sentinelRef}>{isFetchingNextPage ? 'Loading more...' : null}</div>
259 </>
260 )
261}
262```
263β
264## Call Signature
265β
266```ts
267function useInfiniteQuery<TQueryFnData, TError, TData, TQueryKey, TPageParam>(options: UseInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>, queryClient?: QueryClient): UseInfiniteQueryResult<TData, TError>;
268```
269β
270Defined in: [packages/react-query/src/useInfiniteQuery.ts:347](https://github.com/TanStack/query/blob/main/packages/react-query/src/useInfiniteQuery.ts#L347)
271β
272The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of
273`initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`.
274β
275### Type Parameters
276β
277#### TQueryFnData
278β
279`TQueryFnData`
280β
281#### TError
282β
283`TError` = `Error`
284β
285#### TData
286β
287`TData` = [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `unknown`\>
288β
289#### TQueryKey
290β
291`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
292β
293#### TPageParam
294β
295`TPageParam` = `unknown`
296β
297### Parameters
298β
299#### options
300β
301[`UseInfiniteQueryOptions`](../interfaces/UseInfiniteQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\>
302β
303The [UseInfiniteQueryOptions](../interfaces/UseInfiniteQueryOptions.md) to use β everything you can pass to `useInfiniteQuery`.
304β
305#### queryClient?
306β
307[`QueryClient`](../classes/QueryClient.md)
308β
309Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
310be used.
311β
312### Returns
313β
314[`UseInfiniteQueryResult`](../type-aliases/UseInfiniteQueryResult.md)\<`TData`, `TError`\>
315β
316The same properties as `useQuery`, with the addition of `fetchNextPage`, `fetchPreviousPage`,
317`hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and `isFetchingPreviousPage`. `data.pages` and
318`data.pageParams` are also added, as long as a `select` doesn't change `TData` away from its default
319`InfiniteData<TQueryFnData>` shape.
320β
321### Remarks
322β
323Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default
324refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user
325actions, or add conditions like `hasNextPage && !isFetching`.
326β
327### See
328β
329[infiniteQueryOptions](infiniteQueryOptions.md) to share these options between `useInfiniteQuery` and imperative APIs like `queryClient.infiniteQuery`.
330β
331### Examples
332β
333Fetching the next page from a "Load More" button click:
334```tsx
335import { useInfiniteQuery } from '@tanstack/react-query'
336β
337function Projects() {
338 const { data, isPending, isError, error, fetchNextPage, hasNextPage, isFetching, isFetchingNextPage } =
339 useInfiniteQuery({
340 queryKey: ['projects'],
341 queryFn: ({ pageParam }) => fetchProjects(pageParam),
342 initialPageParam: 0,
343 getNextPageParam: (lastPage) => lastPage.nextId,
344 })
345β
346 if (isPending) return 'Loading...'
347 if (isError) return <span>Error: {error.message}</span>
348β
349 return (
350 <>
351 <ul>
352 {data.pages.map((page) =>
353 page.projects.map((project) => <li key={project.id}>{project.name}</li>),
354 )}
355 </ul>
356 <button
357 onClick={() => fetchNextPage()}
358 disabled={!hasNextPage || isFetching}
359 >
360 {isFetchingNextPage
361 ? 'Loading more...'
362 : hasNextPage
363 ? 'Load More'
364 : 'Nothing more to load'}
365 </button>
366 </>
367 )
368}
369```
370β
371Fetching the next page automatically as the user scrolls, using an `IntersectionObserver` on a
372sentinel element after the list:
373```tsx
374import { useInfiniteQuery } from '@tanstack/react-query'
375import { useEffect, useRef } from 'react'
376β
377function Projects() {
378 const {
379 data,
380 isPending,
381 isError,
382 error,
383 fetchNextPage,
384 hasNextPage,
385 isFetching,
386 isFetchingNextPage,
387 } = useInfiniteQuery({
388 queryKey: ['projects'],
389 queryFn: ({ pageParam }) => fetchProjects(pageParam),
390 initialPageParam: 0,
391 getNextPageParam: (lastPage) => lastPage.nextId,
392 })
393β
394 const sentinelRef = useRef<HTMLDivElement>(null)
395β
396 useEffect(() => {
397 const sentinel = sentinelRef.current
398 if (sentinel == null || !hasNextPage || isFetching) return
399β
400 const observer = new IntersectionObserver(([entry]) => {
401 if (entry?.isIntersecting) fetchNextPage()
402 })
403 observer.observe(sentinel)
404β
405 return () => observer.disconnect()
406 }, [hasNextPage, isFetching, fetchNextPage])
407β
408 if (isPending) return 'Loading...'
409 if (isError) return <span>Error: {error.message}</span>
410β
411 return (
412 <>
413 <ul>
414 {data.pages.map((page) =>
415 page.projects.map((project) => <li key={project.id}>{project.name}</li>),
416 )}
417 </ul>
418 <div ref={sentinelRef}>{isFetchingNextPage ? 'Loading more...' : null}</div>
419 </>
420 )
421}
422```
423β
424A query that's disabled, type safe, until `postId` is set β pass `skipToken` as `queryFn`
425instead of setting `enabled: false`:
426```tsx
427import { skipToken, useInfiniteQuery } from '@tanstack/react-query'
428β
429function Comments({ postId }: { postId: string | undefined }) {
430 // Use `isLoading`, not `isPending`, so the loading state doesn't show while the query is disabled.
431 const { data, isLoading, isError, error } = useInfiniteQuery({
432 queryKey: ['post', postId, 'comments'],
433 queryFn:
434 postId != null
435 ? ({ pageParam }) => fetchComments(postId, pageParam)
436 : skipToken,
437 initialPageParam: 0,
438 getNextPageParam: (lastPage) => lastPage.nextId,
439 })
440β
441 if (postId == null) return 'Select a post'
442 if (isLoading) return 'Loading...'
443 if (isError) return <span>Error: {error.message}</span>
444β
445 return (
446 <ul>
447 {data?.pages.map((page) => page.comments.map((c) => <li key={c.id}>{c.text}</li>))}
448 </ul>
449 )
450}
451```