How Virtualization Works

Windowing by Hand

Example

A scroll container with the full height (so the scrollbar is correct) and only the visible rows positioned absolutely inside it. Scroll the list: it has 10,000 items but only a handful of rows exist in the DOM.

import { useState } from 'react';

const items = Array.from({ length: 10000 }, (_, i) => 'Row #' + (i + 1));
const ROW_HEIGHT = 30;
const VIEW_HEIGHT = 150;

export default function App() {
  const [scrollTop, setScrollTop] = useState(0);
  const start = Math.floor(scrollTop / ROW_HEIGHT);
  const visibleCount = Math.ceil(VIEW_HEIGHT / ROW_HEIGHT) + 1;
  const visible = items.slice(start, start + visibleCount);

  return (
    <div>
      <div onScroll={(e) => setScrollTop(e.currentTarget.scrollTop)}
        style={{ height: VIEW_HEIGHT, overflowY: 'auto', border: '1px solid #ccc', position: 'relative' }}>
        <div style={{ height: items.length * ROW_HEIGHT }}>
          {visible.map((text, i) => (
            <div key={start + i} style={{ position: 'absolute', top: (start + i) * ROW_HEIGHT, height: ROW_HEIGHT, left: 8 }}>
              {text}
            </div>
          ))}
        </div>
      </div>
      <p>Rendering {visible.length} of {items.length} rows</p>
    </div>
  );
}

Result