Stop 11 · Connecting React to ExpressTopics · 8/10

Pagination UI in React

Part of the MERN Stack Roadmap

In short

No app sends you 10,000 products in one go. Pagination is how you ask for a small slice at a time, and every list-heavy app you build will need it.

The React side of pagination reads page and total from the API, renders next and previous buttons or page numbers and keeps the current page in the URL.

The jaadu walks out of a library carrying a small stack of books from tall shelves.

Think of it like this

Library books, a few at a time

The college library won't let you carry all 5,000 books home. You borrow a few, return them, then borrow the next few. Pagination works the same way: the server hands you page 1, and you ask for page 2 when you're ready.

Watch it happen

Clicking Next

Post list
API

GET ?_page=1&_limit=10

1/5The list opens with page set to 1 and asks for just ten posts.

The big ideas

What you need to know

Page and limit

?page=3&limit=20 means 'skip the first 40, give me the next 20'. Simple and easy to show as page numbers.

Cursor-based

The server returns a cursor (a bookmark). You send it back to get what comes after. Handles new items better.

Use the total

Many APIs return a total count. Divide by the limit to know how many pages exist.

Infinite scroll

Same idea, but the next page loads automatically when the user reaches the bottom.

See it in code

Walk through the code

tsx
1const [page, setPage] = useState(1);2const [items, setItems] = useState<Post[]>([]);3const LIMIT = 10;4 5useEffect(() => {6  fetch(`/api/posts?_page=${page}&_limit=${LIMIT}`)7    .then((res) => res.json())8    .then(setItems);9}, [page]);10 11<button disabled={page === 1} onClick={() => setPage(page - 1)}>Prev</button>12<button onClick={() => setPage(page + 1)}>Next</button>

1/3The current page and the items live in state. LIMIT is the page size.

page lives in state and sits in the dependency array, so changing it fetches the new slice. JSONPlaceholder uses _page and _limit as its param names.

Save yourself the pain

Common mistakes

Oops

Fetching everything once and slicing it in the browser.

Do this instead

For big data, let the server paginate. Client slicing is only fine for a few hundred items.

Oops

Leaving the Next button active on the last page.

Do this instead

Work out the last page from the total count, or stop when a page comes back with fewer items than the limit.

Your mission

Paginate 100 posts

~25 min

Quick check

With ?page=4&limit=25, which items should the server return?

Go deeper

  1. 1Build next and previous buttons that disable at the first and last page.
  2. 2Store the page in the URL with useSearchParams.
  3. 3Try an infinite scroll version with a Load more button.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge