Virtual Grid Layouts
You'll learn how to extend virtualization techniques to two-dimensional grids, rendering only visible rows and columns for efficient image galleries and data tables.
Beyond Lists: Working in Two Dimensions
So far you've seen virtual scrolling work vertically with lists. But what about grids—like photo galleries or spreadsheet-style data tables? These need both row and column awareness. A virtual grid renders only the cells that fit in the current viewport, dramatically reducing DOM nodes when dealing with thousands or millions of items.
The Core Approach
Think of a virtual grid as nested virtualization: you calculate which rows are visible (just like vertical scrolling), then for each visible row, calculate which columns are visible horizontally.
The calculation looks like:
- Divide
scrollTopby row height to find the first visible row index - Divide
scrollLeftby column width to find the first visible column index - Calculate how many rows and columns fit in the viewport dimensions
- Render only those cells:
grid[row][col]for each visible position
For a 10,000×1,000 grid where only 20 rows and 5 columns are visible, you render just 100 DOM elements instead of 10 million.
Practical Considerations
Positioning: Each cell needs position: absolute with calculated top and left based on its row/column indices and your item dimensions.
Overscan: Buffer a few extra rows/columns beyond the viewport edges (concept you learned earlier) to hide rendering during fast diagonal scrolling.
Variable sizes: Like variable-height lists, variable column widths require tracking cumulative widths for accurate positioning.
Key Takeaway: Virtual grids apply list virtualization principles in two dimensions simultaneously, calculating visible row and column ranges to render only what users see, making massive datasets interactive without performance penalties.