Sobes.tech
Middle

Is it possible to use a library for virtual scrolling? How to implement virtualization via @tanstack/virtual?

sobes.tech AI

Answer from AI

Yes, using a library for virtual scrolling is possible and often necessary to optimize performance when displaying large lists or tables.

@tanstack/virtual is a modern library for list virtualization in React and other frameworks. It allows rendering only the visible part of the elements, reducing the load on the DOM.

Here's a basic example of virtualization with @tanstack/virtual in React:

import React from 'react';
import { useVirtual } from '@tanstack/react-virtual';

function VirtualList({ items }) {
  const parentRef = React.useRef();

  const rowVirtualizer = useVirtual({
    size: items.length,
    parentRef,
    estimateSize: React.useCallback(() => 35, []), // height of one item
  });

  return (
    <div ref={parentRef} style={{ height: `300px`, overflow: 'auto' }}>
      <div style={{ height: `${rowVirtualizer.totalSize}px`, position: 'relative' }}>
        {rowVirtualizer.virtualItems.map(virtualRow => (
          <div
            key={virtualRow.index}
            ref={virtualRow.measureRef}
            style={{
              position: 'absolute',
              top: 0,
              left: 0,
              width: '100%',
              height: `${virtualRow.size}px`,
              transform: `translateY(${virtualRow.start}px)`,
            }}
          >
            {items[virtualRow.index]}
          </div>
        ))}
      </div>
    </div>
  );
}

Thus, the library manages the display of only those elements visible to the user, significantly improving performance when working with large lists.