Adding Server Pagination
Introduction: The Need for Pagination
Welcome back! In the previous lessons, you learned how to fetch and display book data in your React catalog app and how to let users sort the results. As your catalog grows, you might notice that loading and displaying all books at once can slow down your app and make it harder for users to find what they want.
This is where pagination comes in. Pagination means breaking up a large list of items into smaller, more manageable pages. Instead of loading hundreds or thousands of books at once, you only load a few at a time — just what the user needs to see. This makes your app faster and easier to use.
In this lesson, you will learn how to add server-side pagination to your catalog. This means the server will only send a small chunk of books for each page, and your frontend will let users move between pages.
How Server-Side Pagination Works
With server-side pagination, the client (your React app) asks the server for just one page of data at a time. The server responds with only the books for that page, along with information about the total number of books and how many are shown per page.
This is usually done by sending query parameters like page, sortBy, and order in the API request. For example:
The server then responds with something like:
items: The books for the current page.total: The total number of books in the catalog.page: The current page number.pageSize: How many books are shown per page.
This way, your app only needs to handle a small set of books at a time, making it faster and more responsive.
Fetching and Displaying Paginated Data
Let’s look at how you can fetch paginated data and display it in your catalog. Here’s the updated code for your API call and catalog page:
Explanation:
Let’s look at getBooks. It constructs a query string using URLSearchParams so the server receives exactly the sorting, paging, and search options you specify.
- Purpose: Build
/books?...with any mix of:sortBy(e.g.,"title"or"author"),order("asc"or"desc"),page(page number, 1-based),q(free-text search),pageSize(how many items per page — a key focus in this lesson).
- How it’s built:
- Conditional object spreads
...(page ? { page: String(page) } : {})include a key only when a value is present. String(page)andString(pageSize)ensure values are strings, as required by the URL format.new URLSearchParams({...}).toString()encodes and joins the keys/values into a valid query string (e.g.,sortBy=title&order=asc&page=2&pageSize=5).
- Conditional object spreads
- Why
URLSearchParamsmatters: It safely URL-encodes special characters (like spaces inq), avoids manual&concatenation bugs, and guarantees predictable ordering and formatting. - Why emphasize
pageSize: SettingpageSizelets the server trim responses to just N items per page. Here we’ll request 5 in the UI to demonstrate predictable pagination math and navigation performance.
In the next section, we'll see how the frontend uses this.
