When dealing with large datasets in user interfaces, rendering thousands of DOM elements can severely impact performance. Virtual scrolling (or list virtualization) is an optimization technique that solves this problem by only rendering the items that are currently visible to the user.
The core insight is simple: if you have a list of 10,000 items but only 10 are visible in your scrollable container, why render all 10,000? Instead, you calculate which items should be visible based on the current scroll position and only render those items plus a small buffer.
Virtual scrolling works by:
The mathematics are straightforward. If each item is 50px tall and the user has scrolled 1000px down, the first visible item is at index Math.floor(1000 / 50) = 20. If the container shows 400px worth of content, you need to render items 20 through 27, plus your buffer items.
Virtual scrolling is essential for maintaining 60fps performance when dealing with large datasets. Without it, rendering thousands of DOM nodes can cause janky scrolling, high memory usage, and poor user experience.
1// Simple example of calculating visible items
2function getVisibleRange(scrollTop: number, containerHeight: number, itemHeight: number, totalItems: number) {
3 const startIndex = Math.floor(scrollTop / itemHeight);
4 const endIndex = Math.min(
5 totalItems - 1,
6 Math.ceil((scrollTop + containerHeight) / itemHeight) - 1
7 );
8
9 return { startIndex, endIndex };
10}
11
12// Example usage
13const range = getVisibleRange(1000, 400, 50, 10000);
14console.log(range); // { startIndex: 20, endIndex: 27 }