Blog>
Snippets

Optimizing Large Datasets with React Memo and TanStack Virtual

Explain how to use React's memoization feature alongside TanStack Virtual for optimizing the rendering performance of large datasets in a React app.
import { memo } from 'react';
import { useVirtual } from '@tanstack/react-virtual';
Imports memo from React for memoizing components and useVirtual from @tanstack/react-virtual for virtualization.
const Row = memo(({ item }) => <div>{item.text}</div>);
Defines a Row component that accepts an item prop and renders it. The component is wrapped with React.memo to prevent unnecessary re-renders.
const VirtualList = ({ rows }) => {
  const parentRef = React.useRef();
  const rowVirtualizer = useVirtual({
    size: rows.length,
    parentRef,
    estimateSize: React.useCallback(() => 35, []),
  });

  return (
    <div ref={parentRef} style={{ overflow: 'auto', height: '100vh' }}>
      <div style={{ height: rowVirtualizer.totalSize }}>
        {rowVirtualizer.virtualItems.map(virtualRow => (
          <div key={virtualRow.index} style={{
            position: 'absolute',
            top: 0,
            left: 0,
            width: '100%',
            transform: `translateY(${virtualRow.start}px)`
          }}>
            <Row item={rows[virtualRow.index]} />
          </div>
        ))}
      </div>
    </div>
  );
};
Creates a VirtualList component that uses the useVirtual hook from TanStack Virtual. It renders a list of rows using virtualization to improve performance. The list is made up of Row components that are individually memoized.