Open History to see the last commit
1---
2id: infinite-queries
3title: Infinite Queries
4---
5β
6Rendering lists that can additively "load more" data onto an existing set of data or "infinite scroll" is also a very common UI pattern. TanStack Query supports a useful version of `useQuery` called `useInfiniteQuery` for querying these types of lists.
7β
8When using `useInfiniteQuery`, you'll notice a few things are different:
9β
10- `data` is now an object containing infinite query data:
11- `data.pages` array containing the fetched pages
12- `data.pageParams` array containing the page params used to fetch the pages
13- The `fetchNextPage` and `fetchPreviousPage` functions are now available (`fetchNextPage` is required)
14- The `defaultPageParam` option is now available (and required) to specify the initial page param
15- The `getNextPageParam` and `getPreviousPageParam` options are available for both determining if there is more data to load and the information to fetch it. This information is supplied as an additional parameter in the query function
16- A `hasNextPage` boolean is now available and is `true` if `getNextPageParam` returns a value other than `undefined`
17- A `hasPreviousPage` boolean is now available and is `true` if `getPreviousPageParam` returns a value other than `undefined`
18- The `isFetchingNextPage` and `isFetchingPreviousPage` booleans are now available to distinguish between a background refresh state and a loading more state
19β
20> Note: Options `initialData` or `placeholderData` need to conform to the same structure of an object with `data.pages` and `data.pageParams` properties.
21β
22## Example
23β
24Let's assume we have an API that returns pages of `projects` 3 at a time based on a `cursor` index along with a cursor that can be used to fetch the next group of projects:
25β
26```tsx
27fetch('/api/projects?cursor=0')
28// { data: [...], nextCursor: 3}
29fetch('/api/projects?cursor=3')
30// { data: [...], nextCursor: 6}
31fetch('/api/projects?cursor=6')
32// { data: [...], nextCursor: 9}
33fetch('/api/projects?cursor=9')
34// { data: [...] }
35```
36β
37With this information, we can create a "Load More" UI by:
38β
39- Waiting for `useInfiniteQuery` to request the first group of data by default
40- Returning the information for the next query in `getNextPageParam`
41- Calling `fetchNextPage` function
42β
43[//]: # 'Example'
44β
45```tsx
46import { useInfiniteQuery } from '@tanstack/react-query'
47β
48function Projects() {
49 const fetchProjects = async ({ pageParam }) => {
50 const res = await fetch('/api/projects?cursor=' + pageParam)
51 return res.json()
52 }
53β
54 const {
55 data,
56 error,
57 fetchNextPage,
58 hasNextPage,
59 isFetching,
60 isFetchingNextPage,
61 status,
62 } = useInfiniteQuery({
63 queryKey: ['projects'],
64 queryFn: fetchProjects,
65 defaultPageParam: 0,
66 getNextPageParam: (lastPage, pages) => lastPage.nextCursor,
67 })
68β
69 return status === 'pending' ? (
70 <p>Loading...</p>
71 ) : status === 'error' ? (
72 <p>Error: {error.message}</p>
73 ) : (
74 <>
75 {data.pages.map((group, i) => (
76 <React.Fragment key={i}>
77 {group.projects.map((project) => (
78 <p key={project.id}>{project.name}</p>
79 ))}
80 </React.Fragment>
81 ))}
82 <div>
83 <button
84 onClick={() => fetchNextPage()}
85 disabled={!hasNextPage || isFetchingNextPage}
86 >
87 {isFetchingNextPage
88 ? 'Loading more...'
89 : hasNextPage
90 ? 'Load More'
91 : 'Nothing more to load'}
92 </button>
93 </div>
94 <div>{isFetching && !isFetchingNextPage ? 'Fetching...' : null}</div>
95 </>
96 )
97}
98```
99β
100[//]: # 'Example'
101β
102## What happens when an infinite query needs to be refetched?
103β
104When an infinite query becomes `stale` and needs to be refetched, each group is fetched `sequentially`, starting from the first one. This ensures that even if the underlying data is mutated, we're not using stale cursors and potentially getting duplicates or skipping records. If an infinite query's results are ever removed from the queryCache, the pagination restarts at the initial state with only the initial group being requested.
105β
106## What if I want to implement a bi-directional infinite list?
107β
108Bi-directional lists can be implemented by using the `getPreviousPageParam`, `fetchPreviousPage`, `hasPreviousPage` and `isFetchingPreviousPage` properties and functions.
109β
110[//]: # 'Example3'
111β
112```tsx
113useInfiniteQuery({
114 queryKey: ['projects'],
115 queryFn: fetchProjects,
116 defaultPageParam: 0,
117 getNextPageParam: (lastPage, pages) => lastPage.nextCursor,
118 getPreviousPageParam: (firstPage, pages) => firstPage.prevCursor,
119})
120```
121β
122[//]: # 'Example3'
123β
124## What if I want to show the pages in reversed order?
125β
126Sometimes you may want to show the pages in reversed order. If this is case, you can use the `select` option:
127β
128[//]: # 'Example4'
129β
130```tsx
131useInfiniteQuery({
132 queryKey: ['projects'],
133 queryFn: fetchProjects,
134 select: (data) => ({
135 pages: [...data.pages].reverse(),
136 pageParams: [...data.pageParams].reverse(),
137 }),
138})
139```
140β
141[//]: # 'Example4'
142β
143## What if I want to manually update the infinite query?
144β
145Manually removing first page:
146β
147[//]: # 'Example5'
148β
149```tsx
150queryClient.setQueryData(['projects'], (data) => ({
151 pages: data.pages.slice(1),
152 pageParams: data.pageParams.slice(1),
153}))
154```
155β
156[//]: # 'Example5'
157β
158Manually removing a single value from an individual page:
159β
160[//]: # 'Example6'
161β
162```tsx
163const newPagesArray =
164 oldPagesArray?.pages.map((page) =>
165 page.filter((val) => val.id !== updatedId),
166 ) ?? []
167β
168queryClient.setQueryData(['projects'], (data) => ({
169 pages: newPagesArray,
170 pageParams: data.pageParams,
171}))
172```
173β
174[//]: # 'Example6'
175β
176Make sure to keep the same data structure of pages and pageParams!
177β
178[//]: # 'Example7'
179β
180## What if I want to limit the number of pages?
181β
182In some use cases you may want to limit the number of pages stored in the query data to improve the performance and UX:
183β
184- when the user can load a large number of pages (memory usage)
185- when you have to refetch an infinite query that contains dozens of pages (network usage: all the pages are sequentially fetched)
186β
187The solution is to use a "Limited Infinite Query". This is made possible by using the `maxPages` option in conjunction with `getNextPageParam` and `getPreviousPageParam` to allow fetching pages when needed in both directions.
188β
189In the following example only 3 pages are kept in the query data pages array. If a refetch is needed, only 3 pages will be refetched sequentially.
190β
191[//]: # 'Example7'
192β
193```tsx
194useInfiniteQuery({
195 queryKey: ['projects'],
196 queryFn: fetchProjects,
197 defaultPageParam: 0,
198 getNextPageParam: (lastPage, pages) => lastPage.nextCursor,
199 getPreviousPageParam: (firstPage, pages) => firstPage.prevCursor,
200 maxPages: 3,
201})
202```
203β
204## What if my API doesn't return a cursor?
205β
206If your API doesn't return a cursor, you can use the `pageParam` as a cursor. Because `getNextPageParam` and `getPreviousPageParam` also get the `pageParam`of the current page, you can use it to calculate the next / previous page param.
207β
208[//]: # 'Example8'
209β
210```tsx
211return useInfiniteQuery({
212 queryKey: ['projects'],
213 queryFn: fetchProjects,
214 defaultPageParam: 0,
215 getNextPageParam: (lastPage, allPages, lastPageParam) => {
216 if (lastPage.length === 0) {
217 return undefined
218 }
219 return lastPageParam + 1
220 },
221 getPreviousPageParam: (firstPage, allPages, firstPageParam) => {
222 if (firstPageParam <= 1) {
223 return undefined
224 }
225 return firstPageParam - 1
226 },
227})
228```
229β
230[//]: # 'Example8'