Optimize Large React List :👈 👉:Why React Context Can Cause Performance Issues

How to Implement Virtualization for Long Lists

How to Implement Virtualization for Long Lists in React

1. What Is List Virtualization?

List virtualization is a technique in which React renders only the list items currently visible in the browser viewport instead of rendering every item. Consider an application displaying 10,000 employee records.

Without virtualization:

  • React renders all 10,000 employee records.
  • The browser creates thousands of DOM elements.
  • Memory consumption increases.
  • Rendering and scrolling can become slow.

With virtualization:

  • React renders only the visible records.
  • It renders a few additional records outside the visible area for smoother scrolling.
  • As the user scrolls, the visible records are updated.
  • The DOM contains only a small number of rows instead of thousands.

Example: Suppose we have:

  • Total records: 10,000
  • Visible rows: 10
  • Additional rows (overscan): 5
  • Approximately rendered rows: 20

Instead of rendering 10,000 rows, the application renders approximately 20 rows at a time.

2. How Virtualization Works

Virtualization uses the scroll position and row dimensions to calculate which records should be displayed.

Virtual Scrolling Workflow Total Records: 10,000 Scrollable Container Calculate Scroll Position Identify Visible Rows Add Overscan Rows Render Required Rows User Scrolls Down Calculate Again

Important concepts:

  • Viewport: The visible area in which list records are displayed.
  • Scroll position: The current vertical position of the scrollbar.
  • Visible items: The records currently inside the viewport.
  • Overscan: Additional records rendered outside the viewport to reduce visible gaps during scrolling.
  • Total virtual size: The calculated height representing the entire list, even though only a few rows are actually rendered.

3. Popular React Virtualization Libraries

Some commonly used libraries are:

Library Description Use Case
@tanstack/react-virtual Flexible, headless virtualization library. Custom lists, grids and tables.
react-window Lightweight virtualization library. Simple fixed-size and variable-size lists.
react-virtuoso Provides convenient virtualization features. Lists with dynamic heights and more advanced layouts.

In this example, we will use @tanstack/react-virtual.

4. Install the Required Package

Install the library using npm:

npm install @tanstack/react-virtual
Import the required React Hook:
import { useVirtualizer } from "@tanstack/react-virtual";

5. Basic Implementation with Fixed Row Heights

Let's create a simple employee list containing 10,000 records. Step 1: Prepare Sample Data
const employees = Array.from(
    { length: 10000 },
    (_, index) => ({
        id: index + 1,
        name: `Employee ${index + 1}`,
        department: index % 2 === 0 ? "IT" : "HR"
    })
);
This creates 10,000 employee records. Step 2: Implement the Virtualized List
import { useRef } from "react";
import { useVirtualizer } from "@tanstack/react-virtual";
function EmployeeList({ employees }) {
    const parentRef = useRef(null);
    const rowVirtualizer = useVirtualizer({
        count: employees.length,
        getScrollElement: () => parentRef.current,
        estimateSize: () => 60,
        overscan: 5
    });
    return (
        <div
            ref={parentRef}
            style={{
                height: "400px",
                overflow: "auto",
                border: "1px solid gray"
            }}
        >
            <div
                style={{
                    height: rowVirtualizer.getTotalSize(),
                    width: "100%",
                    position: "relative"
                }}
            >
                {rowVirtualizer.getVirtualItems().map(row => {
                    const employee = employees[row.index];
                    return (
                        <div
                            key={employee.id}
                            style={{
                                position: "absolute",
                                top: 0,
                                left: 0,
                                width: "100%",
                                height: row.size,
                                transform: `translateY(${row.start}px)`,
                                boxSizing: "border-box",
                                padding: "10px",
                                borderBottom: "1px solid #ddd"
                            }}
                        >
                            <strong>{employee.name}</strong>
                            <p>{employee.department}</p>
                        </div>
                    );
                })}
            </div>
        </div>
    );
}
export default EmployeeList;
Step 3: Use the Component
function App() {
    const employees = Array.from(
        { length: 10000 },
        (_, index) => ({
            id: index + 1,
            name: `Employee ${index + 1}`,
            department: index % 2 === 0 ? "IT" : "HR"
        })
    );
    return (
        <div>
            <h2>Employee Directory</h2>
            <EmployeeList employees={employees} />
        </div>
    );
}
Result: The application displays a scrollable employee list. Although there are 10,000 records, only the visible records and a few additional rows are rendered.

6. Understanding the Important Properties

Let's understand the configuration used in the previous example. 1. count
count: employees.length
Specifies the total number of records available in the list. 2. getScrollElement
getScrollElement: () => parentRef.current
Returns the DOM element whose scrolling position should control virtualization. In this example, parentRef points to the scrollable div. 3. estimateSize
estimateSize: () => 60
Specifies the estimated height of each row in pixels. Here, each employee row is estimated to be 60 pixels tall. For fixed-height rows, this estimate should match the actual row height. 4. overscan
overscan: 5
Specifies how many additional rows should be rendered outside the visible area. For example:
  • 10 rows are visible.
  • 5 additional rows are rendered before the visible area.
  • 5 additional rows are rendered after the visible area.
  • Approximately 20 rows are rendered.
Overscan improves scrolling smoothness but increasing it also increases the number of rendered elements. 5. getTotalSize()
height: rowVirtualizer.getTotalSize()
Calculates the total virtual height of the complete list. This creates the correct scrollbar size even though only a small number of rows exist in the DOM. 6. getVirtualItems()
rowVirtualizer.getVirtualItems()
Returns the rows that should currently be rendered. Each virtual item contains useful information such as:
  • index: Position of the record in the original collection.
  • start: Vertical starting position of the row.
  • size: Height of the row.
  • end: Ending position of the row.
7. translateY()
transform: `translateY(${row.start}px)`
Positions each rendered row at its correct location within the virtual list. This is important because the rows are rendered independently rather than appearing in their original DOM order.

7. Understanding the CSS Structure

The virtualization implementation uses three important containers.

React Virtualization Layout Scrollable Container Height: 400px overflow: auto Virtual Container Height: Total Virtual List Height position: relative Visible Rows position: absolute transform: translateY(...) Actual Row Content

Scrollable container:

style={{
    height: "400px",
    overflow: "auto"
}}
Provides the viewport and scrollbar. Virtual container:
style={{
    height: rowVirtualizer.getTotalSize(),
    position: "relative"
}}
Maintains the overall scrollable height. Individual rows:
style={{
    position: "absolute",
    top: 0,
    transform: `translateY(${row.start}px)`
}}
Places each visible row at its correct vertical position.

8. Virtualization with Variable Row Heights

In real-world applications, all rows may not have the same height. For example:
  • Employee A: 60 pixels.
  • Employee B: 100 pixels.
  • Employee C: 80 pixels.
For variable-height rows, we can use measureElement to measure the actual rendered height. Example:
import { useRef } from "react";
import { useVirtualizer } from "@tanstack/react-virtual";
function EmployeeList({ employees }) {
    const parentRef = useRef(null);
    const rowVirtualizer = useVirtualizer({
        count: employees.length,
        getScrollElement: () => parentRef.current,
        estimateSize: () => 80,
        overscan: 5
    });
    return (
        <div
            ref={parentRef}
            style={{
                height: "400px",
                overflow: "auto"
            }}
        >
            <div
                style={{
                    height: rowVirtualizer.getTotalSize(),
                    position: "relative"
                }}
            >
                {rowVirtualizer.getVirtualItems().map(row => {
                    const employee = employees[row.index];
                    return (
                        <div
                            key={employee.id}
                            data-index={row.index}
                            ref={rowVirtualizer.measureElement}
                            style={{
                                position: "absolute",
                                top: 0,
                                left: 0,
                                width: "100%",
                                transform: `translateY(${row.start}px)`,
                                padding: "10px",
                                boxSizing: "border-box",
                                borderBottom: "1px solid #ddd"
                            }}
                        >
                            <h4>{employee.name}</h4>
                            <p>{employee.department}</p>
                            <p>{employee.description}</p>
                        </div>
                    );
                })}
            </div>
        </div>
    );
}
Important:
  • data-index identifies the original row index.
  • measureElement allows the virtualizer to measure the actual rendered element.
  • The virtualizer adjusts row positions based on measured dimensions.
  • Estimated heights are used until actual measurements are available.
For dynamic content, use appropriate measurement and test scrolling when images, fonts, or asynchronously loaded content change row dimensions.

9. Virtualization with Search and Filtering

A common requirement is to display a large list with a search box. The important point is that the virtualizer must use the filtered record count, not the original record count. Example:
import { useMemo, useRef, useState } from "react";
import { useVirtualizer } from "@tanstack/react-virtual";
function EmployeeList({ employees }) {
    const parentRef = useRef(null);
    const [search, setSearch] = useState("");
    const filteredEmployees = useMemo(() => {
        return employees.filter(employee =>
            employee.name
                .toLowerCase()
                .includes(search.toLowerCase())
        );
    }, [employees, search]);
    const rowVirtualizer = useVirtualizer({
        count: filteredEmployees.length,
        getScrollElement: () => parentRef.current,
        estimateSize: () => 60,
        overscan: 5
    });
    return (
        <>
            <input
                value={search}
                onChange={e => setSearch(e.target.value)}
                placeholder="Search employees"
            />
            <div
                ref={parentRef}
                style={{
                    height: "400px",
                    overflow: "auto"
                }}
            >
                <div
                    style={{
                        height: rowVirtualizer.getTotalSize(),
                        position: "relative"
                    }}
                >
                    {rowVirtualizer.getVirtualItems().map(row => {
                        const employee = filteredEmployees[row.index];
                        return (
                            <div
                                key={employee.id}
                                style={{
                                    position: "absolute",
                                    top: 0,
                                    left: 0,
                                    width: "100%",
                                    height: row.size,
                                    transform: `translateY(${row.start}px)`,
                                    padding: "10px",
                                    boxSizing: "border-box"
                                }}
                            >
                                {employee.name}
                            </div>
                        );
                    })}
                </div>
            </div>
            <p>
                Total Results: {filteredEmployees.length}
            </p>
        </>
    );
}

Why useMemo? It avoids repeating the filtering calculation when neither the employee collection nor the search value changes. For extremely large datasets, server-side search is generally more appropriate than filtering the entire collection in the browser.

10. Virtualization with Server-Side Data Loading

What if the application has 1 million records? Downloading all one million records into the browser is not a good approach. Instead, use server-side pagination or infinite loading. Example API:

GET /api/employees?page=1&pageSize=100

The backend returns a limited number of records. The frontend can then request additional pages as the user approaches the end of the currently loaded records.
Recommended architecture:

Virtualized Infinite Scrolling React Virtualized List Determine Visible Range Check Loaded Records Request Missing Records ASP.NET Core Web API Database Query Return Requested Records Update React Data Render Visible Rows User Scrolls

Important considerations:

  • Use a cache to avoid requesting the same page repeatedly.
  • Load the next page before the user reaches the end of the currently loaded data.
  • Use AbortController when cancelling obsolete requests.
  • Handle loading, error, and empty states.
  • Use stable record identifiers.
  • Consider cursor-based pagination for very large or frequently changing datasets.

Virtualization and infinite loading solve different problems:

  • Virtualization: Controls how many records are rendered.
  • Infinite loading: Controls when additional records are fetched.

They can be combined in the same application.

11. Common Mistakes to Avoid

1. Incorrect row height If the estimated height is significantly different from the actual height, scrolling positions may be inaccurate until measurements are corrected.

2. Forgetting the total virtual height Without getTotalSize(), the browser does not have the correct scrollable height for the complete list.

3. Forgetting absolute positioning Virtual rows must be positioned using their calculated starting positions. Otherwise, the rows may overlap or appear in the wrong locations.

4. Using array indexes as React keys Prefer stable record IDs. For more advanced use cases, TanStack Virtual also supports a getItemKey configuration.

5. Rendering too many overscan items A very high overscan value reduces the benefit of virtualization because more elements must be rendered.

6. Downloading all records from the backend Virtualization reduces DOM rendering, not network transfer or the memory required to store the complete dataset. Use server-side pagination or infinite loading when necessary.

7. Ignoring accessibility Ensure keyboard navigation, focus handling, and screen-reader access work correctly. Virtualization means some rows are not present in the DOM until needed.

12. When Should You Use Virtualization?

Scenario Recommended approach
50–100 simple records Normal rendering is usually sufficient.
Hundreds of complex records Profile first; consider virtualization.
Thousands of records Virtualization is worth considering.
Very large database result sets Server-side pagination and virtualization.
Continuous scrolling experience Virtualization with infinite loading.
Large data tables Table or grid virtualization.

These are guidelines, not strict thresholds. Actual performance depends on row complexity, device capability, and application requirements.

13. Interview Questions and Answers

Q1. What is virtualization in React? Virtualization is a performance technique that renders only visible list items instead of rendering the entire collection.

Q2. Why do we need virtualization? It reduces the number of DOM elements, memory pressure associated with rendered elements, and unnecessary rendering work, improving performance for long lists.

Q3. What is overscan? Overscan is the number of additional rows rendered outside the visible viewport to make scrolling smoother and reduce the possibility of blank areas during fast scrolling.

Q4. What is the difference between virtualization and pagination? Pagination divides data into pages. Virtualization renders only the visible portion of a scrolling list. Both techniques can be used together.

Q5. What is the purpose of getTotalSize()? It calculates the total virtual height of the list so the scroll container can represent the entire collection.

Q6. What is the purpose of getVirtualItems()? It returns the virtual rows that should currently be rendered based on the scroll position and viewport dimensions.

Q7. How do you handle variable-height rows? Use the virtualizer's measurement functionality, such as measureElement in TanStack Virtual, to measure actual row dimensions and adjust their positions.

Q8. Does virtualization reduce API response size? No. Virtualization only controls rendering. Server-side pagination or filtering is required to reduce the amount of data transferred.

Q9. Can virtualization and infinite scrolling work together? Yes. Virtualization controls how many records are rendered, while infinite loading fetches additional records as the user scrolls.

Q10. Which library would you choose for a new React application? I would evaluate @tanstack/react-virtual for flexible custom virtualization, react-virtuoso for convenient advanced list behavior, and other libraries based on their current maintenance, API, and application requirements.

14. Quick Summary

  • Virtualization: Renders only visible list items.
  • @tanstack/react-virtual: Provides flexible list and grid virtualization.
  • count: Specifies the total number of items.
  • getScrollElement: Identifies the scrollable container.
  • estimateSize: Estimates row height.
  • overscan: Renders additional rows outside the viewport.
  • getTotalSize: Calculates the total virtual list height.
  • getVirtualItems: Returns the rows to render.
  • measureElement: Measures actual row dimensions.

Final takeaway: Virtualization is particularly useful when displaying thousands of records. For enterprise applications, combine virtualization with server-side filtering, sorting, and pagination to achieve better overall performance.

🔙
Optimize Large React List :👈 👉:Why React Context Can Cause Performance Issues

Comments and Discussion