日本語

How to Build a “Load More” Button with React and TanStack Query

​​React​TanStack Query,TypeScript

A "Load more" button under a product list or comment section can be built with useInfiniteQuery from TanStack Query. Loaded pages are appended in order to data.pages, and the button only has to call fetchNextPage. hasNextPage tells you whether another page exists, so you do not have to write that check yourself.

In my test environment, I built a server that returns a list of cats 10 at a time. I recorded what the screen showed when the button was pressed and what requests the server received. I also checked what happens when page 2 fails and when the button is double-clicked.

Note

The test environment was Ubuntu 24.04 with Node.js 22.23.4. I used react and react-dom 19.3.1, @tanstack/react-query 5.107.1, @types/react and @types/react-dom 19.3.0, typescript 7.0.2, and esbuild 0.28.2. I type-checked the .tsx files with tsc, bundled them for production with esbuild, and opened and operated them in Chromium through Playwright 1.63.0. The server was a test Node.js server running on the same machine, and every response waited 400ms before returning. I did not test a development build with StrictMode, browsers other than Chromium, fetchPreviousPage for going back to earlier pages, the display when loading page 1 fails, or a double-click at human speed.

The server returns where to read from next

The test server receives a starting position such as /api/cats?cursor=0, and returns 10 items along with nextCursor, the position to read from next. There are 23 cats in total, so page 3 has 3 items. On the last page, nextCursor is null. This is the response when fetching page 3.

text
$ curl -s 'http://localhost:4173/api/cats?cursor=20'
{"items":[{"id":21,"name":"きなこ(21)"},{"id":22,"name":"あずき(22)"},{"id":23,"name":"もも(23)"}],"nextCursor":null}

The fetch function passed to useInfiniteQuery is as follows. The position to read is received through the pageParam argument. The signal is passed to fetch so that when TanStack Query cancels the query, the network request is also stopped (official guide on query cancellation).

ts
export type Cat = { id: number; name: string };
// One page of the response. If there is no next page, nextCursor is null.
export type CatPage = { items: Cat[]; nextCursor: number | null };

export async function fetchCats({
  pageParam,
  signal,
}: {
  pageParam: number;
  signal: AbortSignal;
}): Promise<CatPage> {
  const res = await fetch(`/api/cats?cursor=${pageParam}`, { signal });
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return res.json();
}

Build the list and button with useInfiniteQuery

This is the whole component. Wrap it in QueryClientProvider when using it. In the test, I created the QueryClient with new QueryClient({ defaultOptions: { queries: { retry: false } } }) so that errors appear on screen right away. According to the official Query Retries guide, the default is to retry up to 3 times, doubling the wait each time starting from 1 second and then 2 seconds, so it takes a while before an error is shown.

tsx
import { useInfiniteQuery } from '@tanstack/react-query';
import { fetchCats } from './api';

export function CatList() {
  const {
    data,
    error,
    fetchNextPage,
    hasNextPage,
    isPending,
    isFetching,
    isFetchingNextPage,
    isFetchNextPageError,
  } = useInfiniteQuery({
    queryKey: ['cats'],
    queryFn: fetchCats,
    initialPageParam: 0,
    getNextPageParam: (lastPage) => lastPage.nextCursor,
  });

  if (isPending) return <p>読み込み中…</p>;
  // Only show an error instead of the list when the first page fails to load.
  if (data === undefined) return <p role="alert">読み込めませんでした({error?.message})</p>;

  // Join the per-page arrays into one single list.
  const cats = data.pages.flatMap((page) => page.items);

  return (
    <>
      <ul>
        {cats.map((cat) => (
          <li key={cat.id}>{cat.name}</li>
        ))}
      </ul>
      {isFetchNextPageError && (
        <p role="alert">続きを読み込めませんでした({error?.message})</p>
      )}
      <button
        type="button"
        onClick={() => fetchNextPage()}
        disabled={!hasNextPage || isFetching}
      >
        {isFetchingNextPage
          ? '読み込み中…'
          : hasNextPage
            ? 'もっと見る'
            : 'これで全部です'}
      </button>
      {isFetching && !isFetchingNextPage && <p>最新の内容に更新中…</p>}
    </>
  );
}

Compared with useQuery, this code uses two additional options:

  • initialPageParam: the pageParam for the first page. Here it is 0.
  • getNextPageParam: a function that receives the last loaded page and returns the pageParam for the next one.

As the official Infinite Queries guide explains, when getNextPageParam returns null or undefined, hasNextPage becomes false. If you return the server's nextCursor as is, hasNextPage becomes false once the last page is loaded, and the disabled condition prevents the button from being pressed.

data.pages is the array of responses, one per page. To display them, flatMap joins them into one array. The button label switches among three states based on isFetchingNextPage (true only while the next page is loading) and hasNextPage.

This is the screen after pressing the button twice. (For the GIF page, the list is laid out in two columns, and the count and click count are shown above it.) The first press brought the list to 20 items and the second to 23. After everything was loaded, the label changed to "That's all" and the button could no longer be pressed.

Screen showing the list growing from 10 to 20 to 23 items after pressing "Load more" twice, with the button finally changing to "That's all"
Pressing 'Load more’ twice to load through to the last page

This is the request log the server received, recorded with Playwright during the same operation. Each button press read once from the next position.

text
サーバー:
      0ms  cursor=0  200
    981ms  cursor=10  200
   1708ms  cursor=20  200

Keep the list when page 2 fails

The official guide's example shows only the error when status === 'error'. I made the server return 500 only for the first request for page 2 (cursor=10) with this approach. The 10 items that had already loaded disappeared, and only the error message remained.

tsx
if (status === 'pending') return <p>読み込み中…</p>;
if (status === 'error') return <p role="alert">読み込めませんでした({error.message})</p>;
text
   1037ms  10件 最後=あずき(10) ボタン「読み込み中…」(押せない)
   1436ms  0件 最後=- ボタンなし 「読み込めませんでした(HTTP 500)」

When loading the next page fails, status becomes 'error' even though page 1 is still in data. The useInfiniteQuery reference describes the error value of status as meaning that the query fetch failed. Whether pages remain is not part of that condition.

So in CatList in the previous section, I show the error in place of the list only when data does not exist yet. A failure on a later page is detected with isFetchNextPageError and shown below the list. Under the same conditions, the 10 items stayed on screen and a message saying the rest could not be loaded (HTTP 500) appeared. The button returned to a state where it could be pressed again. The server responds correctly the second time, so pressing it again loaded page 2.

text
   1430ms  10件 最後=あずき(10) ボタン「もっと見る」(押せる) 「続きを読み込めませんでした(HTTP 500)」
  ---- Press "Load more" (2nd time)
   1770ms  click がボタンに届いた(表示は「もっと見る」)
   1782ms  10件 最後=あずき(10) ボタン「読み込み中…」(押せない) 「続きを読み込めませんでした(HTTP 500)」
   2177ms  20件 最後=こむぎ(20) ボタン「もっと見る」(押せる)

Pressing twice before the screen changes fetches the same page twice

The button has disabled={!hasNextPage || isFetching}. Even so, when I double-clicked the button with Playwright, both clicks reached it. The two clicks were about 2ms apart, and the button only changed to the disabled state after the second click.

text
  ---- Double-click the button
   1029ms  click がボタンに届いた(表示は「もっと見る」)
   1031ms  click がボタンに届いた(表示は「もっと見る」)
   1035ms  10件 最後=あずき(10) ボタン「読み込み中…」(押せない)
   1441ms  20件 最後=こむぎ(20) ボタン「もっと見る」(押せる)
サーバー:
      0ms  cursor=0  200
    967ms  cursor=10  aborted
    974ms  cursor=10  200

The server received two requests for cursor=10, and the first was cut off partway through. If fetchNextPage is called again while a fetch is in progress, the default (cancelRefetch: true) cancels the ongoing fetch and starts it again. Because signal is passed to fetch, the cancelled first request also stopped. The list ended at 20 items, and the same cat never appeared twice.

If you do not want extra requests for the same page, pass { cancelRefetch: false } to fetchNextPage. With this, calling it again during a fetch does not cancel the ongoing one. It does not start a new fetch; it uses the result of the fetch already in progress.

tsx
onClick={() => fetchNextPage({ cancelRefetch: false })}

When I double-clicked with this setting, the server received only one cursor=10 request.

text
サーバー:
      0ms  cursor=0  200
    963ms  cursor=10  200

When re-reading, refetch all pages in order from the first

After reading through 3 pages, I called queryClient.invalidateQueries({ queryKey: ['cats'] }), and the 3 pages were refetched in order from the first. Each next page was requested only after the response for the previous one had arrived.

text
   2389ms  cursor=0  200
   2793ms  cursor=10  200
   3198ms  cursor=20  200

According to the official guide, this behavior keeps the next page position from being decided based on an outdated response. Even if the data changes midway, duplicates and gaps are less likely. The trade-off is that the more pages have been loaded, the longer the re-read takes. In the test, with a server that takes 400ms per page, re-reading 3 pages took about 1.2 seconds. During that time isFetching was true, so the "Updating to the latest content…" message was shown.

For a list with dozens of pages, you can limit how many pages are kept in data.pages with maxPages. The official guide explains that with maxPages: 3, a re-read also covers only 3 pages. The guide's example also specifies getPreviousPageParam, which returns the position of the previous page, so that pages dropped from data.pages can be read back.

​Posted by 86