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. React 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```tsx
45import { useInfiniteQuery } from '@tanstack/react-query'
46β
47function Projects() {
48 const fetchProjects = async ({ pageParam = 0 }) => {
49 const res = await fetch('/api/projects?cursor=' + pageParam);
50 return res.json();
51 }
52β
53 const {
54 data,
55 error,
56 fetchNextPage,
57 hasNextPage,
58 isFetching,
59 isFetchingNextPage,
60 status,
61 } = useInfiniteQuery(['projects'], fetchProjects, {
62 getNextPageParam: (lastPage, pages) => lastPage.nextCursor,
63 })
64β
65 return status === 'loading' ? (
66 <p>Loading...</p>
67 ) : status === 'error' ? (
68 <p>Error: {error.message}</p>
69 ) : (
70 <>
71 {data.pages.map((group, i) => (
72 <React.Fragment key={i}>
73 {group.projects.map(project => (
74 <p key={project.id}>{project.name}</p>
75 ))}
76 </React.Fragment>
77 ))}
78 <div>
79 <button
80 onClick={() => fetchNextPage()}
81 disabled={!hasNextPage || isFetchingNextPage}
82 >
83 {isFetchingNextPage
84 ? 'Loading more...'
85 : hasNextPage
86 ? 'Load More'
87 : 'Nothing more to load'}
88 </button>
89 </div>
90 <div>{isFetching && !isFetchingNextPage ? 'Fetching...' : null}</div>
91 </>
92 )
93}
94```
95β
96## What happens when an infinite query needs to be refetched?
97β
98When 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.
99β
100### refetchPage
101β
102If you only want to actively refetch a subset of all pages, you can pass the `refetchPage` function to `refetch` returned from `useInfiniteQuery`.
103β
104```tsx
105const { refetch } = useInfiniteQuery(['projects'], fetchProjects, {
106 getNextPageParam: (lastPage, pages) => lastPage.nextCursor,
107})
108β
109// only refetch the first page
110refetch({ refetchPage: (page, index) => index === 0 })
111```
112β
113You 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).
114β
115**Signature**
116β
117- `refetchPage: (page: TData, index: number, allPages: TData[]) => boolean`
118β
119The function is executed for each page, and only pages where this function returns `true` will be refetched.
120β
121## What if I need to pass custom information to my query function?
122β
123By 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:
124β
125```tsx
126function Projects() {
127 const fetchProjects = ({ pageParam = 0 }) =>
128 fetch('/api/projects?cursor=' + pageParam)
129β
130 const {
131 status,
132 data,
133 isFetching,
134 isFetchingNextPage,
135 fetchNextPage,
136 hasNextPage,
137 } = useInfiniteQuery(['projects'], fetchProjects, {
138 getNextPageParam: (lastPage, pages) => lastPage.nextCursor,
139 })
140β
141 // Pass your own page param
142 const skipToCursor50 = () => fetchNextPage({ pageParam: 50 })
143}
144```
145β
146## What if I want to implement a bi-directional infinite list?
147β
148Bi-directional lists can be implemented by using the `getPreviousPageParam`, `fetchPreviousPage`, `hasPreviousPage` and `isFetchingPreviousPage` properties and functions.
149β
150```tsx
151useInfiniteQuery(['projects'], fetchProjects, {
152 getNextPageParam: (lastPage, pages) => lastPage.nextCursor,
153 getPreviousPageParam: (firstPage, pages) => firstPage.prevCursor,
154})
155```
156β
157## What if I want to show the pages in reversed order?
158β
159Sometimes you may want to show the pages in reversed order. If this is case, you can use the `select` option:
160β
161```tsx
162useInfiniteQuery(['projects'], fetchProjects, {
163 select: data => ({
164 pages: [...data.pages].reverse(),
165 pageParams: [...data.pageParams].reverse(),
166 }),
167})
168```
169β
170## What if I want to manually update the infinite query?
171β
172Manually removing first page:
173β
174```tsx
175queryClient.setQueryData(['projects'], data => ({
176 pages: data.pages.slice(1),
177 pageParams: data.pageParams.slice(1),
178}))
179```
180β
181Manually removing a single value from an individual page:
182β
183```tsx
184const newPagesArray = oldPagesArray?.pages.map((page) =>
185 page.filter((val) => val.id !== updatedId)
186) ?? []
187β
188queryClient.setQueryData(['projects'], data => ({
189 pages: newPagesArray,
190 pageParams: data.pageParams,
191}))
192```
193β
194Make sure to keep the same data structure of pages and pageParams!