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

useInfiniteQuery.md

451 lines13.2 KB

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 )
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 )
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 )
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 )
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 )
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 )
451```