Open History to see the last commit
1---
2id: paginated-queries
3title: Paginated / Lagged Queries
4---
5β
6Rendering paginated data is a very common UI pattern and in TanStack Query, it "just works" by including the page information in the query key:
7β
8[//]: # 'Example'
9```tsx
10const result = useQuery({
11 queryKey: ['projects', page],
12 queryFn: fetchProjects
13})
14```
15[//]: # 'Example'
16β
17However, if you run this simple example, you might notice something strange:
18β
19**The UI jumps in and out of the `success` and `pending` states because each new page is treated like a brand new query.**
20β
21This experience is not optimal and unfortunately is how many tools today insist on working. But not TanStack Query! As you may have guessed, TanStack Query comes with an awesome feature called `placeholderData` that allows us to get around this.
22β
23## Better Paginated Queries with `placeholderData`
24β
25Consider the following example where we would ideally want to increment a pageIndex (or cursor) for a query. If we were to use `useQuery`, **it would still technically work fine**, but the UI would jump in and out of the `success` and `pending` states as different queries are created and destroyed for each page or cursor. By setting `placeholderData` to `(previousData) => previousData` or `keepPreviousData` function exported from TanStack Query, we get a few new things:
26β
27- **The data from the last successful fetch is available while new data is being requested, even though the query key has changed**.
28- When the new data arrives, the previous `data` is seamlessly swapped to show the new data.
29- `isPlaceholderData` is made available to know what data the query is currently providing you
30β
31[//]: # 'Example2'
32```tsx
33function Todos() {
34 const [page, setPage] = React.useState(0)
35β
36 const fetchProjects = (page = 0) => fetch('/api/projects?page=' + page).then((res) => res.json())
37β
38 const {
39 isPending,
40 isError,
41 error,
42 data,
43 isFetching,
44 isPlaceholderData,
45 } = useQuery({
46 queryKey: ['projects', page],
47 queryFn: () => fetchProjects(page),
48 placeholderData: keepPreviousData,
49 })
50β
51 return (
52 <div>
53 {isPending ? (
54 <div>Loading...</div>
55 ) : isError ? (
56 <div>Error: {error.message}</div>
57 ) : (
58 <div>
59 {data.projects.map(project => (
60 <p key={project.id}>{project.name}</p>
61 ))}
62 </div>
63 )}
64 <span>Current Page: {page + 1}</span>
65 <button
66 onClick={() => setPage(old => Math.max(old - 1, 0))}
67 disabled={page === 0}
68 >
69 Previous Page
70 </button>{' '}
71 <button
72 onClick={() => {
73 if (!isPlaceholderData && data.hasMore) {
74 setPage(old => old + 1)
75 }
76 }}
77 // Disable the Next Page button until we know a next page is available
78 disabled={isPlaceholderData || !data?.hasMore}
79 >
80 Next Page
81 </button>
82 {isFetching ? <span> Loading...</span> : null}{' '}
83 </div>
84 )
85}
86```
87[//]: # 'Example2'
88β
89## Lagging Infinite Query results with `placeholderData`
90β
91While not as common, the `placeholderData` option also works flawlessly with the `useInfiniteQuery` hook, so you can seamlessly allow your users to continue to see cached data while infinite query keys change over time.