Paginated / Lagged Queries

· abundance's blog


Rendering paginated data is a very common UI pattern and in TanStack Query, it "just works" by including the page information in the query key:

1const result = useQuery({
2  queryKey: ['projects', page],
3  queryFn: fetchProjects,
4})

However, if you run this simple example, you might notice something strange:

The UI jumps in and out of the success and pending states because each new page is treated like a brand new query.

This 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.

Better Paginated Queries with placeholderData #

Consider 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:

 1import { keepPreviousData, useQuery } from '@tanstack/react-query'
 2import React from 'react'
 3
 4function Todos() {
 5  const [page, setPage] = React.useState(0)
 6
 7  const fetchProjects = (page = 0) =>
 8    fetch('/api/projects?page=' + page).then((res) => res.json())
 9
10  const { isPending, isError, error, data, isFetching, isPlaceholderData } =
11    useQuery({
12      queryKey: ['projects', page],
13      queryFn: () => fetchProjects(page),
14      placeholderData: keepPreviousData,
15    })
16
17  return (
18    <div>
19      {isPending ? (
20        <div>Loading...</div>
21      ) : isError ? (
22        <div>Error: {error.message}</div>
23      ) : (
24        <div>
25          {data.projects.map((project) => (
26            <p key={project.id}>{project.name}</p>
27          ))}
28        </div>
29      )}
30      <span>Current Page: {page + 1}</span>
31      <button
32        onClick={() => setPage((old) => Math.max(old - 1, 0))}
33        disabled={page === 0}
34      >
35        Previous Page
36      </button>
37      <button
38        onClick={() => {
39          if (!isPlaceholderData && data.hasMore) {
40            setPage((old) => old + 1)
41          }
42        }}
43        // Disable the Next Page button until we know a next page is available
44        disabled={isPlaceholderData || !data?.hasMore}
45      >
46        Next Page
47      </button>
48      {isFetching ? <span> Loading...</span> : null}
49    </div>
50  )
51}

Lagging Infinite Query results with placeholderData #

While 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.