Optimizing Large Lists with TanStack Config
Implement a strategy for virtualizing a large list component in a React application using TanStack Config to manage the state efficiently.
import { useVirtualizer } from '@tanstack/react-virtual';
import React, { useRef, useState } from 'react';
Import the necessary hooks from React and the useVirtualizer hook from @tanstack/react-virtual library.
const VirtualList = ({ items }) => {
const parentRef = useRef();
const rowVirtualizer = useVirtualizer({
count: items.length,
getScrollElement: () => parentRef.current,
estimateSize: () => 35, // Height of each row in pixels
});
return (
<div ref={parentRef} style={{ height: `300px`, overflow: 'auto' }}>
<div style={{
height: rowVirtualizer.getTotalSize(), width: '100%', position: 'relative'
}}>
{rowVirtualizer.getVirtualItems().map(virtualRow => (
<div
key={virtualRow.key}
style={{
position: 'absolute',
top: 0,
left: 0,
width: '100%',
transform: `translateY(${virtualRow.start}px)`,
height: `${virtualRow.size}px`
}}
>
{items[virtualRow.index]}
</div>
))}
</div>
</div>
);
};
Defines a VirtualList component. It uses the useVirtualizer hook to virtualize the items passed to it, rendering only the items that fit in the current viewport + buffer. The parentRef is connected to the scrolling container, and rowVirtualizer controls the virtualization process.
export default function App() {
const items = Array.from({ length: 10000 }, (_, i) => `Item ${i}`);
return <VirtualList items={items} />;
}
Defines the App component that creates a large list of items and renders it using the VirtualList component, showcasing the virtualization.