Implementing Row Virtualization
Illustrates how to apply virtualization within React TanStack Table to render only rows currently visible in the viewport, enhancing performance when dealing with large datasets.
import { useVirtualizer } from '@tanstack/react-virtual';
import { useRef } from 'react';
Imports the useVirtualizer hook from TanStack's React Virtual and useRef hook from React.
const parentRef = useRef();
Creates a ref for the parent container to track its scroll position.
const rowVirtualizer = useVirtualizer({
count: yourData.length,
getScrollElement: () => parentRef.current,
estimateSize: () => 35,
overscan: 5,
});
Initializes the row virtualizer with your data's length, a function to get the scrolling element, an estimated size for each row (in pixels), and an overscan value for pre-rendering rows outside the viewport.
<div ref={parentRef} style={{ height: '400px', overflow: 'auto' }}>
<div style={{ height: `${rowVirtualizer.getTotalSize()}px`, width: '100%', position: 'relative' }}>
{rowVirtualizer.getVirtualItems().map(virtualRow => (
<div key={virtualRow.index} style={{
position: 'absolute',
top: 0,
left: 0,
width: '100%',
transform: `translateY(${virtualRow.start}px)`
}}>
{yourData[virtualRow.index]}
</div>
))}
</div>
</div>
Renders the virtualized rows within a container. Uses the total size calculated by the virtualizer for the container's height and absolutely positions each virtualized row based on its start position.