How to Implement Pagination in React

    Feb 2, 202510 min read90 viewsUpdated:Feb 3, 2025
    How to Implement Pagination in React

    Implementing pagination in a React application can be a game changer for improving user experience, especially when dealing with large datasets that fetch data.

    This blog will walk you through how to implement pagination effectively, complete with code snippets and detailed explanations. Let's dive into it!

    What is Pagination?

    what is pagination

    Pagination is the process of dividing large datasets or content into smaller, more manageable chunks, referred to as pages, and displaying them one at a time. This technique is particularly important in web applications, where presenting an overwhelming amount of data on a single screen can lead to a poor user experience.

    By breaking the data into discrete pages, pagination helps improve data storage, performance, usability, and accessibility.

    In applications like e-commerce platforms, blogs, or dashboards, datasets can include thousands or even millions of records, such as a catalog of products, a list of users, or an archive of articles. Without pagination, displaying all this data at once could slow down the application and make it challenging for users to find specific information.

    Pagination ensures that only a subset of data, typically a few records per page, is loaded and displayed at any page link at any one-page number at a given time.

    Example of React Pagination

    For instance, consider a news website with thousands of articles. Without pagination, loading all articles currently displayed page simultaneously would not only consume significant bandwidth but also overwhelm users trying to navigate the content. Pagination solves this by allowing users to navigate between multiple pages, that display, say, 10 or 20 articles at a time, making the browsing experience smoother and more intuitive.

    Moreover, pagination plays a critical role in maintaining the aesthetic and functional design of applications. It provides users with clear navigation controls, such as "Next" and "Previous" buttons or numbered page links, allowing them to browse the dataset at their own pace.

    By organizing data effectively, pagination enhances user experience and ensures the application remains responsive and efficient.

    Why is Pagination Important?

    Pagination is a cornerstone of effective web and application design, offering a structured way to manage large datasets. It goes beyond dividing content into pages, delivering significant benefits for both users and developers. Here’s why pagination is important:

    why is pagination important

    Improves Performance

    By loading only a subset of the previous page or data at a time, pagination reduces load times and optimizes resource usage. It ensures smooth application performance, even for large datasets, while reducing the strain on client devices and servers.

    Simplifies Navigation

    Pagination organizes data into smaller sections, making it easier for users to browse and find what they need. Clear navigation options, like page numbers or “Next” buttons above code, provide a structured and intuitive experience.

    Enhances Scalability

    As data sets grow, pagination handles them seamlessly by fetching data page by single page only. It also provides valuable analytics, helping developers improve content organization and user experience.

    Understanding Pagination in React

    React makes it easy to implement pagination with reusable components, state management, and hooks. Let's explore how.

    Core Concepts of Pagination

    • Total Pages: Total number of pages based on the dataset and items per page.

    • Current Page: The currently active page.

    • Page Size: Number of items displayed per page.

    Setting Up Your React Environment

    First, ensure you have a basic React app set up. If not, run the following commands:

    npx create-react-app pagination-demo  
    cd pagination-demo  
    npm start  

    Fetching Data for Pagination

    For this example, we will be data fetching process data from a placeholder API:

    const fetchData = async (page, limit) => {
      const response = await fetch(`https://jsonplaceholder.typicode.com/posts?_page=${page}&_limit=${limit}`);
      return await response.json();
    };

    State Management for Pagination

    To manage the current page loading state and data, use React's useState and useEffect:

    import React, { useState, useEffect } from 'react';
    
    const PaginatedList = () => {
      const [data, setData] = useState([]);
      const [currentPage, setCurrentPage] = useState(1);
      const itemsPerPage = 10;
    
      useEffect(() => {
        fetchData(currentPage, itemsPerPage).then(setData);
      }, [currentPage]);
    
      return <div>{/* Render components here */}</div>;
    };

    Creating a Pagination Component

    Define a reusable Pagination component:

    const Pagination = ({ totalPages, currentPage, onPageChange }) => {
      const pages = Array.from({ length: totalPages }, (_, i) => i + 1);
    return (
        <div>
          {pages.map(page => (
            <button
              key={page}
              disabled={page === currentPage}
              onClick={() => onPageChange(page)}
            >
              {page}
            </button>
          ))}
        </div>
      );
    };

    Displaying Paginated Data

    Incorporate your Pagination component into the main component:

    const PaginatedList = () => {
      const [data, setData] = useState([]);
      const [currentPage, setCurrentPage] = useState(1);
      const itemsPerPage = 10;
      const totalPages = 10; // Replace with dynamic calculation
    
      useEffect(() => {
        fetchData(currentPage, itemsPerPage).then(setData);
      }, [currentPage]);
    
      return (
        <div>
          <ul>
            {data.map(item => (
              <li key={item.id}>{item.title}</li>
            ))}
          </ul>
          <Pagination
            totalPages={totalPages}
            currentPage={currentPage}
            onPageChange={setCurrentPage}
          />
        </div>
      );
    };

    Handling Page Navigation

    Use a function to update the page change the currentPage state:

    const handlePageChange = (page) => {
      setCurrentPage(page);
    };

    Customizing Pagination Controls

    Add "Next" and "Previous" buttons for better navigation:

    const Pagination = ({ totalPages, currentPage, onPageChange }) => {
      return (
        <div>
          <button
            disabled={currentPage === 1}
            onClick={() => onPageChange(currentPage - 1)}
          >
            Previous
          </button>
          {Array.from({ length: totalPages }, (_, i) => i + 1).map(page => (
            <button
              key={page}
              disabled={page === currentPage}
              onClick={() => onPageChange(page)}
            >
              {page}
            </button>
          ))}
          <button
            disabled={currentPage === totalPages}
            onClick={() => onPageChange(currentPage + 1)}
          >
            Next
          </button>
        </div>
      );
    };

    Server-Side vs. Client-Side Pagination

    server side vs. client-side pagination

    Pagination can be implemented in two primary ways: Client-Side Pagination and Server-Side Pagination. Each method has its advantages and disadvantages, and the choice depends on factors such as the size of your dataset, the capabilities of your server, and the expected user experience. Let's dive deeper into each approach to understand how they work and when to use them.

    Client-Side Pagination

    Client-side pagination involves fetching the entire dataset from the server at once and handling the pagination logic on the client side, typically within the browser. Here, the core pagination logic is done purely through JavaScript on the front end.

    How It Works:

    1. When the application loads, it makes a single API request to fetch all the data.

    2. The data is stored in the client’s memory, often in state management tools like React’s useState or libraries like Redux.

    3. Pagination logic, such as dividing the data into pages or calculating the total number of pages, is executed on the client side.

    4. Users can navigate between pages without requiring additional API calls since all the data is already available locally.

    Advantages of Client-Side Pagination:

    • Reduced Server Load: The server only needs to process a single request, regardless of how many pages the user navigates.

    • Faster Page Navigation: Since all the data is already on the client side, moving between pages is instant and doesn't require any network requests.

    • Simple to Implement: It requires fewer backend changes since most of the logic is handled in the front end.

    • Ideal for Small Datasets: If the dataset is relatively small (e.g., less than a few thousand records), this approach is efficient.

    Disadvantages of Client-Side Pagination:

    • Performance Issues with Large Datasets: Loading large datasets into the browser can lead to increased memory usage and slower rendering times, which can degrade the user experience.

    • Increased Initial Load Time: Fetching all the data at once can result in a slower initial page load, especially with a poor internet connection.

    • Security Concerns: Exposing all data to the client can make it vulnerable to unauthorized access, especially if sensitive data is included.

    Server-Side Pagination

    Server-side pagination, on the other hand, fetches only the data required for the current and next page up. Each time the user navigates to a new page, a request is sent to the server to retrieve the page item corresponding data.

    How It Works:

    1. When the application loads, it makes an API request to fetch only the data for the first page, along with metadata such as the total number of records and pages.

    2. Each time the user navigates to a different page, another API request is made to fetch the specific data for that page.

    3. The server processes the request, fetches the relevant subset of data from the database, and returns it to the client.

    Advantages of Server-Side Pagination:

    • Handles Large Datasets Efficiently: Since only a small subset of data is sent to the client at a time, the browser doesn’t need to handle large datasets, improving performance.

    • Reduced Initial Load Time: The initial request is faster because it only retrieves the data for the first page instead of the entire dataset.

    • Scalable for Growing Datasets: This approach is more suitable for applications where the dataset size can grow significantly over time.

    • Better Control Over Data Security: By fetching data page by page, only the required records are exposed to the client, reducing the risk of unauthorized access.

    Disadvantages of Server-Side Pagination:

    • Additional Server Load: The server must handle multiple API requests as users navigate through the pages, which can increase server load.

    • Slower Page Navigation: Each page change requires a network request, leading to a slight delay while waiting for the server’s response.

    • More Complex Backend Implementation: Server-side pagination often requires modifications to the backend API and database queries, such as using SQL's LIMIT and OFFSET clauses.

    Integrating Pagination with APIs

    Modify the API call to support server-side pagination:

    const fetchData = async (page, limit) => {
      const response = await fetch(`https://api.example.com/data?page=${page}&limit=${limit}`);
      return await response.json();
    };

    Styling Pagination Components

    Use CSS or libraries like Tailwind to style pagination controls.

    .pagination {
      display: flex;
      justify-content: center;
    }
    
    .pagination button {
      margin: 0 5px;
      padding: 5px 10px;
    }

    Adding Accessibility to Pagination

    Ensure buttons are keyboard-navigable and include aria-labels.

    <button
      aria-label={`Go to page ${page}`}
      key={page}
      disabled={page === currentPage}
      onClick={() => onPageChange(page)}
    >
      {page}
    </button>

    Testing Pagination Features

    Manually test page navigation, data rendering specific page names, and edge cases like empty datasets or out-of-range pages.

    Common Challenges in Pagination

    • Data Sync Issues: Ensure the API response matches the requested page.

    • Styling Overlap: Design responsive components.

    Optimizing Performance

    • Use lazy loading or infinite scrolling for datasets with thousands of items.

    • Implement caching to store previously fetched data.

    Libraries Used for Pagination in React

    Implementing pagination manually is a great way to learn the fundamentals. However, in real-world applications, leveraging libraries can speed up development and add advanced features.

    Below are some popular libraries for pagination in React:

    React Paginate

    React Paginate is one of the most popular libraries for adding custom pagination component to React applications. It provides a ready-to-use pagination component with customizable styles and functionality.

    Key Features:

    • Easy integration with API data.

    • Supports server-side and client-side pagination.

    • Fully customizable pagination controls.

    import ReactPaginate from 'react-paginate';
    
    const PaginationExample = ({ totalPages, onPageChange }) => (
      <ReactPaginate
        pageCount={totalPages}
        pageRangeDisplayed={5}
        marginPagesDisplayed={2}
        onPageChange={(selectedItem) => onPageChange(selectedItem.selected + 1)}
        containerClassName="pagination"
        activeClassName="active"
      />
    );

    Material-UI Pagination

    Material-UI (MUI) is a popular UI framework for React, and it includes a robust pagination component. If you are already using MUI in an app component of your project, this component integrates seamlessly.

    Key Features:

    • Part of a larger component library.

    • Fully styled out-of-the-box with Material Design guidelines.

    • Supports advanced pagination features like rows per page and item ranges.

    import { Pagination } from '@mui/material';
    
    const MaterialPagination = ({ totalPages, onPageChange }) => (
      <Pagination
        count={totalPages}
        color="primary"
        onChange={(event, page) => onPageChange(page)}
      />
    );

    React-Paginate-Hook

    For those who prefer hooks over components, React-Paginate-Hook provides a functional approach to the pagination hook.

    Key Features:

    • Lightweight and minimalistic.

    • Ideal for custom UI implementations.

    • Easy to use with other hooks.

    import usePagination from 'react-paginate-hook';
    
    const PaginationExample = ({ totalItems, itemsPerPage }) => {
      const { currentPage, pages, nextPage, previousPage, setPage } = usePagination({
        totalItems,
        itemsPerPage,
      });
    
      return (
        <div>
          <button onClick={previousPage}>Previous</button>
          {pages.map((page) => (
            <button key={page} onClick={() => setPage(page)}>
              {page}
            </button>
          ))}
          <button onClick={nextPage}>Next</button>
        </div>
      );
    };

    React Bootstrap Pagination

    React Bootstrap is a React wrapper for the popular Bootstrap framework. It includes a Pagination component that adheres to Bootstrap's design principles.

    Key Features:

    • Pre-styled pagination controls.

    • Customizable with Bootstrap classes.

    • Integrates well with other Bootstrap components.

    import Pagination from 'react-bootstrap/Pagination';
    
    const BootstrapPagination = ({ totalPages, currentPage, onPageChange }) => {
      const items = [];
      for (let number = 1; number <= totalPages; number++) {
        items.push(
          <Pagination.Item
            key={number}
            active={number === currentPage}
            onClick={() => onPageChange(number)}
          >
            {number}
          </Pagination.Item>
        );
      }
    
      return <Pagination>{items}</Pagination>;
    };

    Conclusion

    Choosing the right library for pagination in your React project depends on your specific needs. If you’re looking for simplicity, libraries like React Paginate are ideal.

    For broader UI capabilities, consider Material-UI or React Bootstrap. If your application demands table management with pagination, React Table is a great choice.

    These libraries reduce the complexity of building pagination from scratch while allowing room for customization and scalability. Try them out in your next project!

    24

    Related articles

    This website uses cookies to analyze website traffic and optimize your website experience. By continuing, you agree to our use of cookies as described in our Privacy Policy.