ReactMedium

Pagination implementation

Pagination splits a list into pages and lets users move between them. Keep the current page (ideally in the URL), compute totalPages from the total count and page size, fetch or slice only the current page, and render previous and next buttons plus a compact range of page numbers with ellipses. Server-side pagination is the norm for real data.

Client-side vs server-side

  • Client-side: all data is already loaded; slice with items.slice((page - 1) * size, page * size). Fine for small datasets.
  • Server-side: request ?page=2&limit=20 (offset) or ?cursor=abc (cursor) and render what comes back. Needed for large or changing data.

Implementation points

  • Store page in the URL (useSearchParams) so it survives reloads and can be shared; validate and clamp it.
  • totalPages = Math.max(1, Math.ceil(total / pageSize)).
  • Disable "Previous" on page 1 and "Next" on the last page.
  • Show a window of page numbers around the current page with ellipses for long ranges.
  • Keep previous data visible while the next page loads (TanStack Query placeholderData: keepPreviousData) to avoid layout jumps.
  • Reset to page 1 when filters change.
  • Scroll to the top of the list after changing pages and move focus for keyboard users.

Accessibility

Wrap controls in <nav aria-label="Pagination">, mark the current page with aria-current="page", and give buttons clear labels.

Code example

tsx
1import { useSearchParams } from "react-router";
2
3function pageRange(current: number, total: number, delta = 1): (number | "…")[] {
4 const pages: (number | "…")[] = [];
5 for (let p = 1; p <= total; p++) {
6 if (p === 1 || p === total || Math.abs(p - current) <= delta) pages.push(p);
7 else if (pages[pages.length - 1] !== "…") pages.push("…");
8 }
9 return pages;
10}
11
12export function Pagination({ total, pageSize = 20 }: { total: number; pageSize?: number }) {
13 const [params, setParams] = useSearchParams();
14 const totalPages = Math.max(1, Math.ceil(total / pageSize));
15 const page = Math.min(totalPages, Math.max(1, Number(params.get("page")) || 1)); // validate + clamp
16
17 const go = (p: number) => {
18 setParams((prev) => { prev.set("page", String(p)); return prev; });
19 window.scrollTo({ top: 0, behavior: "smooth" });
20 };
21
22 return (
23 <nav aria-label="Pagination">
24 <button disabled={page === 1} onClick={() => go(page - 1)}>Previous</button>
25 {pageRange(page, totalPages).map((p, i) =>
26 p === "…" ? <span key={`gap-${i}`}>…</span> : (
27 <button key={p} aria-current={p === page ? "page" : undefined} onClick={() => go(p)}>{p}</button>
28 )
29 )}
30 <button disabled={page === totalPages} onClick={() => go(page + 1)}>Next</button>
31 </nav>
32 );
33}
34
35// Data for the current page (server-side):
36// useQuery({ queryKey: ["orders", page], queryFn: () => fetch(`/api/orders?page=${page}&limit=20`).then(r => r.json()),
37// placeholderData: keepPreviousData });

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app