Setting Up TanStack Virtual for a Basic Virtual List
Demonstrate how to install TanStack Virtual and set up a simple virtual list in a React component.
npm i @tanstack/react-virtual@beta
First, install TanStack Virtual for React by running this command in your terminal. This is required to utilize virtualization in your project.
import { useVirtualizer } from '@tanstack/react-virtual';
import React, { useRef } from 'react';
Import useVirtualizer from TanStack Virtual and useRef from React to create a reference for the scrolling container.
const items = new Array(10000).fill(null).map((_, i) => `Item ${i}`);
Generate an array of 10,000 items to simulate a large dataset. This array will be used to render our virtual list.
const VirtualList = () => {
const parentRef = useRef();
const rowVirtualizer = useVirtualizer({
count: items.length,
getScrollElement: () => parentRef.current,
estimateSize: () => 35,
overscan: 5,
});
return (
<div ref={parentRef} style={{ height: `400px`, width: `300px`, overflow: 'auto' }}>
<div style={{ height: `${rowVirtualizer.getTotalSize()}px`, width: '100%', position: 'relative' }}>
{rowVirtualizer.getVirtualItems().map(virtualRow => (
<div key={virtualRow.index} style={{ position: 'absolute', top: `${virtualRow.start}px`, left: 0, width: '100%', height: `${virtualRow.size}px` }}>
{items[virtualRow.index]}
</div>
))}
</div>
</div>
);
};
Define a VirtualList component. Use useRef to attach a reference to the parent container. useVirtualizer is used to set up the virtualization behavior including item count, a method to get the scrollable element, item size estimation, and overscan. Render a scrollable div as the parent, using a virtualized approach to only render visible items and few outside the viewport for smoother scrolling. Virtual items are positioned absolutely within a container whose height matches the total size of all items.
export default VirtualList;
Finally, export the VirtualList component so it can be used elsewhere in your application.