Virtual scrolling chỉ render items visible trong viewport (~20-50 nodes) bất kể list có hàng nghìn items — dùng @tanstack/react-virtual; chỉ cần khi list >100-200 items phức tạp, profile trước.
- Virtual scrolling (windowing) chỉ render DOM nodes cho items visible trong viewport — list 10,000 items chỉ render 20-50 items trong DOM tại bất kỳ thời điểm nào, maintain scroll position qua spacer elements.
- Mechanism: total height của list được set bằng container (tạo scrollbar đúng size), khi scroll, calculate which items should be visible, render chỉ those items với absolute positioning.
- Libraries: @tanstack/react-virtual (headless, flexible, không opinionated về UI — phổ biến nhất hiện tại); react-window (Brian Vaughn, smaller, simpler API cho fixed-size items); react-virtuoso (dynamic item heights, auto-measure).
- Khi cần dùng: list >100-200 items với complex rendering (images, many DOM nodes per item); performance profiling (React DevTools Profiler hoặc Chrome Performance tab) cho thấy list rendering là bottleneck — đừng premature optimize.
- Lưu ý: virtual scrolling phức tạp hơn regular list — khó implement features như 'scroll to item', dynamic item heights, sticky headers; @tanstack/react-virtual có examples cho tất cả cases này.
- Variable height items: cần measure items sau render để tính scroll position — @tanstack/react-virtual và react-virtuoso handle dynamic heights tốt hơn react-window.
- Alternative đơn giản hơn khi list không quá dài: pagination hoặc 'load more' button — ít phức tạp, không cần virtual scrolling.
Virtual scrolling renders only items visible in the viewport (~20-50 nodes) regardless of list size — use @tanstack/react-virtual; only needed when lists have >100-200 complex items, always profile first.
- Virtual scrolling (windowing) renders DOM nodes only for items visible in the viewport — a list of 10,000 items renders only 20-50 nodes in the DOM at any given time, maintaining scroll position via spacer elements.
- Mechanism: the total height of the list is set on the container (creating the correct scrollbar size); on scroll, calculate which items should be visible and render only those items with absolute positioning.
- Libraries: @tanstack/react-virtual (headless, flexible, unopinionated about UI — most popular today); react-window (Brian Vaughn, smaller, simpler API for fixed-size items); react-virtuoso (dynamic item heights, auto-measurement).
- When to use: lists with >100-200 items that have complex rendering (images, many DOM nodes per item); performance profiling (React DevTools Profiler or Chrome Performance tab) shows list rendering is the bottleneck — do not optimize prematurely.
Pitfall: virtual scrolling is more complex than a regular list — features like 'scroll to item', dynamic item heights, and sticky headers are harder to implement; @tanstack/react-virtual has examples for all these cases.