R

React Handbook

Clean • Professional

React Large Lists: Pagination, Infinite Scroll & Windowing

2 minute

Handling Large Lists in React

Rendering large lists in React can cause performance issues, slow UI, and high memory usage if not handled efficiently. Proper handling techniques like pagination, infinite scroll, and windowing can optimize performance and improve user experience.

Challenges with Large Lists

Rendering hundreds or thousands of items at once can lead to:

  • Slow rendering – the browser takes longer to paint elements
  • High memory usage – each element consumes resources
  • Poor user experience – lagging UI, slow scroll, or delayed updates

React provides strategies to efficiently manage large datasets.

Pagination

Pagination splits the list into pages and only renders a subset at a time.

Example – Simple Pagination:

import React, { useState } from "react";

function PaginatedList({ items, itemsPerPage }) {
  const [currentPage, setCurrentPage] = useState(1);

  const startIndex = (currentPage - 1) * itemsPerPage;
  const currentItems = items.slice(startIndex, startIndex + itemsPerPage);

  return (
    <div>
      <ul>
        {currentItems.map((item, index) => (
          <li key={index}>{item}</li>
        ))}
      </ul>
      <buttondisabled={currentPage === 1}
        onClick={() => setCurrentPage(currentPage - 1)}>Prev</button>
      <buttondisabled={startIndex + itemsPerPage >= items.length}
        onClick={() => setCurrentPage(currentPage + 1)}>Next</button>
    </div>
  );
}

Infinite Scroll

Infinite scroll loads more items as the user scrolls down the page. This is commonly used in social media feeds.

Example – Basic Infinite Scroll:

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

function InfiniteList({ items, batchSize }) {
  const [visibleItems, setVisibleItems] = useState(items.slice(0, batchSize));

  const loadMore = () => {
    setVisibleItems(prev => items.slice(0, prev.length + batchSize));
  };

  return (
    <divstyle={{ height: "400px", overflow: "auto" }}
      onScroll={(e) => {
        const { scrollTop, scrollHeight, clientHeight } = e.currentTarget;
        if (scrollTop + clientHeight >= scrollHeight) loadMore();
      }}
    >
      <ul>
        {visibleItems.map((item, index) => (
          <li key={index}>{item}</li>
        ))}
      </ul>
    </div>
  );
}

Windowing / Virtualization

Windowing (or virtualization) only renders the visible portion of a list and reuses DOM nodes as the user scrolls. Libraries like React Window and React Virtualized make this simple.

Example – React Window:

import { FixedSizeList as List } from "react-window";

const Row = ({ index, style }) => <div style={style}>Item {index}</div>;

function VirtualizedList() {
  return (
    <Listheight={400}
      itemCount={1000}
      itemSize={35}
      width={300}
    >
      {Row}
    </List>
  );
}

 

Article 0 of 0