Installing and Setting Up TanStack Virtual
Showcase code for how to install TanStack Virtual library and initialize a simple fixed list in a React component.
npm install @tanstack/react-virtual
This command installs the TanStack Virtual library for React, which is used for efficiently rendering large lists and tabular data by virtualizing rows that are not currently in the viewport.
import React from 'react';
import { useVirtualizer } from '@tanstack/react-virtual';
function App() {
const parentRef = React.useRef();
const rowVirtualizer = useVirtualizer({
count: 10000, // The number of items in the list
getScrollElement: () => parentRef.current,
estimateSize: () => 35, // The estimated size of each item
overscan: 5,
});
return (
<div
ref={parentRef}
style={{
height: `500px`,
width: `100%`,
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)`,
height: `${virtualRow.size}px`
}}
>
Row {virtualRow.index}
</div>
))}
</div>
</div>
);
}
This code snippet demonstrates how to use the TanStack Virtual library to create a simple virtualized list within a React component. It initializes the virtualizer with a specified number of items, dynamically calculates their position based on scroll, and renders only the items that are currently visible to the user, improving performance for large lists.