Virtualization renders only visible items, reducing DOM nodes for large lists.
Using react-window:
1import { FixedSizeList } from "react-window";23const Row = ({ index, style }) => (4 <div style={style} className="row">5 Item {index}6 </div>7);89function VirtualList() {10 return (11 <FixedSizeList12 height={500}13 width="100%"14 itemCount={10000}15 itemSize={50}16 >17 {Row}18 </FixedSizeList>19 );20}
Using @tanstack/react-virtual:
1import { useVirtualizer } from "@tanstack/react-virtual";2import { useRef } from "react";34function VirtualList({ items }) {5 const parentRef = useRef<HTMLDivElement>(null);67 const virtualizer = useVirtualizer({8 count: items.length,9 getScrollElement: () => parentRef.current,10 estimateSize: () => 50,11 overscan: 5,12 });1314 return (15 <div ref={parentRef} style={{ height: "500px", overflow: "auto" }}>16 <div style={{ height: `${virtualizer.getTotalSize()}px`, position: "relative" }}>17 {virtualizer.getVirtualItems().map((virtualRow) => (18 <div19 key={virtualRow.index}20 style={{21 position: "absolute",22 top: 0,23 left: 0,24 width: "100%",25 height: `${virtualRow.size}px`,26 transform: `translateY(${virtualRow.start}px)`,27 }}28 >29 {items[virtualRow.index]}30 </div>31 ))}32 </div>33 </div>34 );35}
Benefits:
When to use: