DEV Community

Cover image for Efficient Pagination in React: Best Practices for API Calls
Oge Obubu
Oge Obubu

Posted on

Efficient Pagination in React: Best Practices for API Calls

Introduction

Pagination is a common feature in web applications. It allows users to navigate large datasets without being overwhelmed by information, however, if this is not done properly pagination can lead to performance issues and a frustrating user experience. In this post, we'll explore best practices for managing pagination in React applications, especially when they're interactive with backend API.

Understanding Pagination

When dealing with large data sets it is important to divide information into parts that can be managed. Pagination allows users to view a subset of items at a time. This makes navigation easier and more intuitive. However, continuously fetching data from the server every time the user clicks to navigate can cause unnecessary stress on both the client and server.

Why Avoid Continuous API Calls?

  1. Performance concerns: Frequent API calls can slow down your application. As a result, users must wait longer.

  2. Server load: Too many requests can overwhelm the server. This results in reduced performance or even crashing.

  3. User Experience: Loading and unloading data quickly can create a jarring experience for users.

Best Practices for Efficient Pagination

  1. Debounce API Calls
    Using the debounce mechanism can help limit the frequency of API calls. This technique delays the execution of API requests until the user has paused interacting with the pagination control.

  2. Local Caching
    Caching previously retrieved data helps to display items quickly without additional API calls by storing the results locally. You can give users immediate feedback when they return to previously viewed pages.

  3. Prefetching data
    Try prefetching data for adjacent pages. When the user is on page N, you can load data from pages N+1 and N-1 in the background. So when they click "Next" or "Previous" the information is already there. This results in a smoother experience.

  4. Loading indicator
    Always provide feedback to users when retrieving data. Loading the spinner or message will inform the user that their action is being performed. This will help improve the overall experience.

Implementing Efficient Pagination in React

Here's a simple example of how to effectively use page scheduling in React applications:

import React, { useState, useEffect } from 'react';

const PaginatedList = () => {
  const [items, setItems] = useState([]);
  const [page, setPage] = useState(1);
  const [totalPages, setTotalPages] = useState(0);
  const [cache, setCache] = useState({});

  async function fetchItems(page) {
    if (cache[page]) {
      setItems(cache[page]);
      return;
    }

    const response = await fetch(`/api/items?page=${page}&limit=10`);
    const data = await response.json();
    setCache(prev => ({ ...prev, [page]: data.items }));
    setItems(data.items);
    setTotalPages(data.totalPages);
  };

  useEffect(() => {
    fetchItems(page);
  }, [page]);

  function handleNext() {
    if (page < totalPages) {
      setPage(page + 1);
    }
  };

  function handlePrevious() {
    if (page > 1) {
      setPage(page - 1);
    }
  };

  return (
    <>
      <ul>
        {items.map(item => (
          <li key={item.id}>{item.name}</li>
        ))}
      </ul>
      <div>
        <button onClick={handlePrevious} disabled={page === 1}>Previous</button>
        <span> Page {page} of {totalPages} </span>
        <button onClick={handleNext} disabled={page === totalPages}>Next</button>
      </div>
    </>
  );
};

export default PaginatedList;
Enter fullscreen mode Exit fullscreen mode

Code Description

  • State management: We manage the current page. Total number of pages and archiving of previously retrieved items.

  • Fetching data: The fetchItems function checks if the requested page is cached. If so, we will use accumulated data, otherwise, an API call will be made.

  • Pagination controls: Simple navigation buttons allow users to move between pages, with checks to prevent navigating beyond the existing page.

Conclusion

Using effective page scheduling in your React application not only increases performance but also improves performance. But it also greatly improves the user experience. By avoiding unnecessary API calls through techniques such as caching and prefetching. You can create a smooth interface that attracts users.

By following these best practices You can be sure that your pagination isn't just functional. But it's also powerful and easy to use. Happy coding!

Top comments (0)