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
14- 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 (which can optionally be overridden when calling the `fetchNextPage` or `fetchPreviousPage` functions)
15- A `hasNextPage` boolean is now available and is `true` if `getNextPageParam` returns a value other than `undefined`
16- A `hasPreviousPage` boolean is now available and is `true` if `getPreviousPageParam` returns a value other than `undefined`
17- The `isFetchingNextPage` and `isFetchingPreviousPage` booleans are now available to distinguish between a background refresh state and a loading more state
18β
19> Note: When using options like `initialData` or `select` in your query, make sure that when you restructure your data that it still includes `data.pages` and `data.pageParams` properties, otherwise your changes will be overwritten by the query in its return!
20β
21## Example
22β
23Let'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:
24β
25```tsx
26fetch('/api/projects?cursor=0')
27// { data: [...], nextCursor: 3}
28fetch('/api/projects?cursor=3')
29// { data: [...], nextCursor: 6}
30fetch('/api/projects?cursor=6')
31// { data: [...], nextCursor: 9}
32fetch('/api/projects?cursor=9')
33// { data: [...] }
34```
35β
36With this information, we can create a "Load More" UI by:
37β
38- Waiting for `useInfiniteQuery` to request the first group of data by default
39- Returning the information for the next query in `getNextPageParam`
40- Calling `fetchNextPage` function
41β
42> Note: It's very important you do not call `fetchNextPage` with arguments unless you want them to override the `pageParam` data returned from the `getNextPageParam` function. e.g. Do not do this: `<button onClick={fetchNextPage} />` as this would send the onClick event to the `fetchNextPage` function.
43β
44[//]: # 'Example'
45β
46```tsx
47import { useInfiniteQuery } from '@tanstack/react-query'
48β
49function Projects() {
50 const fetchProjects = async ({ pageParam = 0 }) => {
51 const res = await fetch('/api/projects?cursor=' + pageParam)
52 return res.json()
53 }
54β
55 const {
56 data,
57 error,
58 fetchNextPage,
59 hasNextPage,
60 isFetching,
61 isFetchingNextPage,
62 status,
63 } = useInfiniteQuery({
64 queryKey: ['projects'],
65 queryFn: fetchProjects,
66 getNextPageParam: (lastPage, pages) => lastPage.nextCursor,
67 })
68β
69 return status === 'loading' ? (
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### refetchPage
107β
108If you only want to actively refetch a subset of all pages, you can pass the `refetchPage` function to `refetch` returned from `useInfiniteQuery`.
109β
110[//]: # 'Example2'
111β
112```tsx
113const { refetch } = useInfiniteQuery({
114 queryKey: ['projects'],
115 queryFn: fetchProjects,
116 getNextPageParam: (lastPage, pages) => lastPage.nextCursor,
117})
118β
119// only refetch the first page
120refetch({ refetchPage: (page, index) => index === 0 })
121```
122β
123[//]: # 'Example2'
124β
125You can also pass this function as part of the 2nd argument (`queryFilters`) to [queryClient.refetchQueries](../reference/QueryClient#queryclientrefetchqueries), [queryClient.invalidateQueries](../reference/QueryClient#queryclientinvalidatequeries) or [queryClient.resetQueries](../reference/QueryClient#queryclientresetqueries).
126β
127**Signature**
128β
129- `refetchPage: (page: TData, index: number, allPages: TData[]) => boolean`
130β
131The function is executed for each page, and only pages where this function returns `true` will be refetched.
132β
133## What if I need to pass custom information to my query function?
134β
135By default, the variable returned from `getNextPageParam` will be supplied to the query function, but in some cases, you may want to override this. You can pass custom variables to the `fetchNextPage` function which will override the default variable like so:
136β
137[//]: # 'Example3'
138β
139```tsx
140function Projects() {
141 const fetchProjects = ({ pageParam = 0 }) =>
142 fetch('/api/projects?cursor=' + pageParam)
143β
144 const {
145 status,
146 data,
147 isFetching,
148 isFetchingNextPage,
149 fetchNextPage,
150 hasNextPage,
151 } = useInfiniteQuery({
152 queryKey: ['projects'],
153 queryFn: fetchProjects,
154 getNextPageParam: (lastPage, pages) => lastPage.nextCursor,
155 })
156β
157 // Pass your own page param
158 const skipToCursor50 = () => fetchNextPage({ pageParam: 50 })
159}
160```
161β
162[//]: # 'Example3'
163β
164## What if I want to implement a bi-directional infinite list?
165β
166Bi-directional lists can be implemented by using the `getPreviousPageParam`, `fetchPreviousPage`, `hasPreviousPage` and `isFetchingPreviousPage` properties and functions.
167β
168[//]: # 'Example4'
169β
170```tsx
171useInfiniteQuery({
172 queryKey: ['projects'],
173 queryFn: fetchProjects,
174 getNextPageParam: (lastPage, pages) => lastPage.nextCursor,
175 getPreviousPageParam: (firstPage, pages) => firstPage.prevCursor,
176})
177```
178β
179[//]: # 'Example4'
180β
181## What if I want to show the pages in reversed order?
182β
183Sometimes you may want to show the pages in reversed order. If this is case, you can use the `select` option:
184β
185[//]: # 'Example5'
186β
187```tsx
188useInfiniteQuery({
189 queryKey: ['projects'],
190 queryFn: fetchProjects,
191 select: (data) => ({
192 pages: [...data.pages].reverse(),
193 pageParams: [...data.pageParams].reverse(),
194 }),
195})
196```
197β
198[//]: # 'Example5'
199β
200## What if I want to manually update the infinite query?
201β
202Manually removing first page:
203β
204[//]: # 'Example6'
205β
206```tsx
207queryClient.setQueryData(['projects'], (data) => ({
208 pages: data.pages.slice(1),
209 pageParams: data.pageParams.slice(1),
210}))
211```
212β
213[//]: # 'Example6'
214β
215Manually removing a single value from an individual page:
216β
217[//]: # 'Example7'
218β
219```tsx
220const newPagesArray =
221 oldPagesArray?.pages.map((page) =>
222 page.filter((val) => val.id !== updatedId),
223 ) ?? []
224β
225queryClient.setQueryData(['projects'], (data) => ({
226 pages: newPagesArray,
227 pageParams: data.pageParams,
228}))
229```
230β
231[//]: # 'Example7'
232β
233Make sure to keep the same data structure of pages and pageParams!