React
Beginner
1 min read
Virtualisation for Long Lists
Example
// Using @tanstack/react-virtual
import { useVirtualizer } from '@tanstack/react-virtual';
import { useRef } from 'react';
const ALL_ITEMS = Array.from({ length: 10_000 }, (_, i) => ({
id: i,
label: `Item #${i + 1}`,
}));
function VirtualList() {
const parentRef = useRef(null);
const virtualizer = useVirtualizer({
count: ALL_ITEMS.length,
getScrollElement: () => parentRef.current,
estimateSize: () => 40, // estimated row height in px
overscan: 5, // extra items above/below viewport
});
return (
<div
ref={parentRef}
style={{ height: 500, overflow: 'auto' }}
>
{/* Total scrollable area */}
<div style={{ height: virtualizer.getTotalSize(), position: 'relative' }}>
{virtualizer.getVirtualItems().map(virtualRow => (
<div
key={virtualRow.key}
style={{
position: 'absolute',
top: 0,
left: 0,
width: '100%',
height: virtualRow.size,
transform: `translateY(${virtualRow.start}px)`,
}}
>
{ALL_ITEMS[virtualRow.index].label}
</div>
))}
</div>
</div>
);
}