Sobes.tech
Middle

How does list virtualization work? How is it technically implemented through JavaScript?

sobes.tech AI

Answer from AI

Virtualization of a list is an optimization technique for displaying long lists in an interface, where only the elements visible to the user are rendered in the DOM, and the rest are not. This significantly reduces the load on the browser and improves performance.

Technically, in JavaScript, it is implemented as follows:

  1. The size of the container and the height of one list item are tracked.
  2. It is calculated how many items fit into the visible area.
  3. Only these items are rendered in the DOM, plus a small buffer at the top and bottom for smooth scrolling.
  4. When scrolling, the set of displayed items is updated, and the container is given a total height so that the scrollbar corresponds to the full list.

An example of a simplified implementation in React:

function VirtualList({ items, itemHeight, height }) {
  const [scrollTop, setScrollTop] = React.useState(0);
  const totalHeight = items.length * itemHeight;
  const startIndex = Math.floor(scrollTop / itemHeight);
  const visibleCount = Math.ceil(height / itemHeight);
  const visibleItems = items.slice(startIndex, startIndex + visibleCount);

  const offsetY = startIndex * itemHeight;

  return (
    <div style={{ height, overflowY: 'auto' }} onScroll={e => setScrollTop(e.currentTarget.scrollTop)}>
      <div style={{ height: totalHeight, position: 'relative' }}>
        <div style={{ transform: `translateY(${offsetY}px)`, position: 'absolute', top: 0, left: 0, right: 0 }}>
          {visibleItems.map(item => (
            <div key={item.id} style={{ height: itemHeight }}>
              {item.content}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

Thus, the browser works only with a small number of elements, which improves performance when working with large lists.

How does list virtualization work? How is it… - sobes.tech