@virtualgrid/lib
v1.0.0
Published
A React hook-based library for efficient grid virtualization
Maintainers
Readme
@virtualgrid/lib
React virtualization library for rendering large datasets using CSS Grid.
This package contains the core Virtual Grid hook and utilities. It only renders visible items on screen and automatically adapts to CSS Grid layout changes through ResizeObserver, making it suitable for responsive grids, image galleries, and carousels.
Installation
npm install @virtualgrid/lib
# or
yarn add @virtualgrid/libQuick Start
import { useVirtualGrid } from '@virtualgrid/lib'
function Grid() {
const data = Array.from({ length: 10_000 }, (_, i) => ({ id: i, name: `Item ${i}` }))
const {
items,
styles,
gridRef,
scrollRef,
} = useVirtualGrid({
data,
gap: 20,
padding: [20, 20, 20, 20],
offScreenPages: 1,
})
return (
<div ref={scrollRef} style={{ height: '100vh', overflow: 'auto' }}>
<div ref={gridRef} style={styles} className="grid">
{items.map((item) => (
<div key={item.id}>{item.name}</div>
))}
</div>
</div>
)
}API Overview
import type { VirtualGrid, VirtualGridProps } from '@virtualgrid/lib'
function useVirtualGrid<T>(props: VirtualGridProps<T>): VirtualGrid<T>VirtualGridProps<T>
data: T[]– Items to virtualize (required)offScreenPages?: number– Number of pages to render outside the viewportpadding?: number[]–[top, right, bottom, left]padding; must match your CSS paddinggap?: number– Gap between grid items; must match your CSSgaphorizontal?: boolean– Enable horizontal scrolling
VirtualGrid<T>
Core return shape (simplified):
items: T[]– Visible items to renderstyles: React.CSSProperties– Styles to apply to the grid containergridRef: React.RefObject<HTMLDivElement | null>scrollRef: React.RefObject<HTMLDivElement | null>page: numberpageRange: number[]onScrollTo(page: number): void- Layout fields (scroll sizes, grid dimensions, etc.)
For full details, see the exported types:
import { VirtualGrid, VirtualGridProps, Layout } from '@virtualgrid/lib'Key Concepts
- Padding-based positioning – Uses dynamic padding instead of absolute positioning to maintain scroll position while letting CSS Grid handle layout.
- Resize-aware – Uses
ResizeObserverto react to container and layout changes. - Page-based virtualization – Renders only the current and surrounding pages, controlled by
offScreenPages.
Limitations
- Not designed for masonry layouts (requires predictable item height).
- Works best when items have uniform sizes.
- CSS
gapandpaddingmust match the values passed to the hook.
Development
From the repo root:
yarn install
yarn dev:libTo run tests for this package:
cd packages/lib
yarn test