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β
10```tsx
11const result = useQuery({
12 queryKey: ['projects', page],
13 queryFn: fetchProjects,
14})
15```
16β
17[//]: # 'Example'
18β
19However, if you run this simple example, you might notice something strange:
20β
21**The UI jumps in and out of the `success` and `pending` states because each new page is treated like a brand new query.**
22β
23This 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.
24β
25## Better Paginated Queries with `placeholderData`
26β
27Consider 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:
28β
29- **The data from the last successful fetch is available while new data is being requested, even though the query key has changed**.
30- When the new data arrives, the previous `data` is seamlessly swapped to show the new data.
31- `isPlaceholderData` is made available to know what data the query is currently providing you
32β
33[//]: # 'Example2'
34β
35```tsx
36import { keepPreviousData, useQuery } from '@tanstack/react-query'
37import React from 'react'
38β
39function Todos() {
40 const [page, setPage] = React.useState(0)
41β
42 const fetchProjects = (page = 0) =>
43 fetch('/api/projects?page=' + page).then((res) => res.json())
44β
45 const { isPending, isError, error, data, isFetching, isPlaceholderData } =
46 useQuery({
47 queryKey: ['projects', page],
48 queryFn: () => fetchProjects(page),
49 placeholderData: keepPreviousData,
50 })
51β
52 return (
53 <div>
54 {isPending ? (
55 <div>Loading...</div>
56 ) : isError ? (
57 <div>Error: {error.message}</div>
58 ) : (
59 <div>
60 {data.projects.map((project) => (
61 <p key={project.id}>{project.name}</p>
62 ))}
63 </div>
64 )}
65 <span>Current Page: {page + 1}</span>
66 <button
67 onClick={() => setPage((old) => Math.max(old - 1, 0))}
68 disabled={page === 0}
69 >
70 Previous Page
71 </button>
72 <button
73 onClick={() => {
74 if (!isPlaceholderData && data.hasMore) {
75 setPage((old) => old + 1)
76 }
77 }}
78 // Disable the Next Page button until we know a next page is available
79 disabled={isPlaceholderData || !data?.hasMore}
80 >
81 Next Page
82 </button>
83 {isFetching ? <span> Loading...</span> : null}
84 </div>
85 )
86}
87```
88β
89[//]: # 'Example2'
90β
91## Lagging Infinite Query results with `placeholderData`
92β
93While 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.