Skip to content

Build a paginated user list in React

A working component that fetches a page, renders rows, and uses the v3 cursor to render Previous/Next correctly.

Pagination on a list endpoint is one of the most common patterns in any UI, and also one of the most common places to get details wrong. This recipe builds it step by step: a working Previous/Next first, then URL sync so deep links work, then a page-jump option for long lists. Every step uses the meta object that GoRest v3 returns.

The meta you need

Every list response from GoRest v3 is an object with two keys, data and meta:

{
  "data": [ { "id": "0190a8e4-0000-7000-8000-000000000001", "name": "Aarav Sharma", "email": "aarav.sharma@example.com", "status": "active" } ],
  "meta": { "has_more": true, "next_cursor": "eyJ2Ijoi...", "total": null }
}
  • meta.has_more is true when there is another page after this one.
  • meta.next_cursor is an opaque string. Send it back as page[after] to get the next page.
  • meta.total is the total number of rows. It is null unless you ask for it with page[count]=true.
  • The page size is page[size], from 1 to 100. The default is 25.

There are no X-Pagination-* headers in v3. The next page link is also in the Link header with rel="next".

Use meta.has_more to disable Next on the last page. Without it, you have to guess, and guessing wrong means a "Next" button that returns an empty list.

The minimal component

A cursor only moves forward. So to support Previous, keep a stack of the cursors you used. The cursor for page 1 is null. State: the stack, the rows and the meta of the current page.

import { useState, useEffect } from "react";

function UserList() {
  const [cursors, setCursors] = useState([null]);   // cursors[i] opens page i + 1
  const [users, setUsers]     = useState([]);
  const [meta, setMeta]       = useState({ has_more: false, next_cursor: null });
  const [busy, setBusy]       = useState(false);

  const page = cursors.length;
  const cursor = cursors[cursors.length - 1];

  useEffect(() => {
    const url = new URL("https://gorest.co.in/public/v3/users");
    url.searchParams.set("page[size]", "10");
    if (cursor) url.searchParams.set("page[after]", cursor);

    setBusy(true);
    fetch(url)
      .then(res => res.json())
      .then(body => {
        setUsers(body.data);
        setMeta(body.meta);
      })
      .finally(() => setBusy(false));
  }, [cursor]);

  return (
    <div>
      <table>
        <thead>
          <tr><th>Name</th><th>Email</th><th>Status</th></tr>
        </thead>
        <tbody>
          {users.map(u => (
            <tr key={u.id}>
              <td>{u.name}</td>
              <td>{u.email}</td>
              <td>{u.status}</td>
            </tr>
          ))}
        </tbody>
      </table>

      <nav className="pagination">
        <button onClick={() => setCursors(c => c.slice(0, -1))} disabled={page <= 1 || busy}>
          Previous
        </button>
        <span>Page {page}</span>
        <button onClick={() => setCursors(c => [...c, meta.next_cursor])} disabled={!meta.has_more || busy}>
          Next
        </button>
      </nav>
    </div>
  );
}

A few details worth pointing out:

  • disabled on Previous when you are on the first page and on Next when meta.has_more is false. Cheaper than guessing.
  • Previous just drops the last cursor from the stack. The effect then runs again with the earlier cursor and fetches that page.
  • The busy flag prevents double-clicks during fetch. Skip this, and impatient users fire off two requests for the same page.
  • Cursor paging does not show "Page 3 of 12" by default. If you need a count, add page[count]=true to the first request and read meta.total.

Sync to the URL

Pagination state belongs in the URL so users can copy a link, refresh, or hit the back button to return to a specific page. With a cursor, the URL holds the cursor itself. It is safe to put in a URL.

import { useSearchParams } from "react-router-dom";

function UserList() {
  const [params, setParams] = useSearchParams();
  const cursor = params.get("after");   // null means the first page

  function goNext(nextCursor) {
    setParams({ after: nextCursor });   // the browser Back button returns to the earlier page
  }
  // ...same fetch as before, keyed on `cursor`
}

The fetch effect now keys on cursor derived from params. Hitting "Next" updates the URL, which updates cursor, which triggers the effect, which fetches the next page. The URL is the single source of truth. Use the browser Back button as Previous, or keep the stack of cursors if you want a Previous button too.

Page-jump with offset paging

For lists where users must jump to page 47, cursors are not enough, because you cannot build a cursor yourself. v3 also has offset paging for this case. Send page[number] and page[count]=true:

/public/v3/users?page[size]=10&page[number]=47&page[count]=true

meta.total then gives the row count, so the page count is Math.ceil(meta.total / size). Two rules: page[number] cannot be sent together with page[after], and in offset mode meta.next_cursor is null, so use has_more and the page number to move on.

function PageJump({ page, total, setPage }) {
  const visible = pageWindow(page, total, 5); // [1, 2, 3, 4, 5]

  return (
    <ul className="pagination">
      {visible.map(n => (
        <li key={n}>
          <button
            aria-current={n === page ? "page" : undefined}
            onClick={() => setPage(n)}
            disabled={n === page}>
            {n}
          </button>
        </li>
      ))}
    </ul>
  );
}

function pageWindow(current, total, size) {
  const half = Math.floor(size / 2);
  let start = Math.max(1, current - half);
  let end   = Math.min(total, start + size - 1);
  start = Math.max(1, end - size + 1);
  return Array.from({ length: end - start + 1 }, (_, i) => start + i);
}

The pageWindow helper centres a 5-page window around the current page, clamped to the valid range. Page 1 shows [1, 2, 3, 4, 5], page 50 of 100 shows [48, 49, 50, 51, 52], and the last page shows the last 5. Offset paging can repeat or skip rows if rows are added while the user browses. Use cursors when that matters, and offsets when jumping matters.

Filtering and pagination together

When the user changes a filter (status, search term), start again from the first page; otherwise an old cursor or page number points into the wrong list. Make filter changes go through a single state setter that resets the cursor stack:

function setFilter(next) { setStatus(next); setCursors([null]); }

Send the filter as filter[status]=active on every page request. A cursor is tied to the query that made it, so do not reuse it with another filter or another sort.

Pre-fetch the next page

A nice extra: when the user is on page 3, fetch page 4 in the background so clicking Next feels instant. Use a separate useEffect that fires when the page is stable; cache the result keyed on meta.next_cursor.

Common mistakes

  • Building cursors yourself. The cursor is opaque. Only use the value from meta.next_cursor.
  • Calculating total client-side. Some devs read the array length on each page and try to derive the total; it cannot work, since you only have one page's worth. Ask for page[count]=true and read meta.total.
  • Forgetting the busy state. Without it, the user can spam Next, and your component races on which response arrives first.
  • Storing pagination in state alone. Without URL sync, your page does not survive a refresh. Always use URL params for shareable state.
  • Not resetting on filter change. The filter narrows the results, the user is on a late page, and the cursor no longer fits: confusing.
More recipes

Keep building