Blog>
Snippets

Optimizing Large Data Sets with Virtualization

Provide an example of integrating virtualization in React TanStack Table to render only visible rows, enhancing performance with large data sets.
import { useTable } from '@tanstack/react-table';
import { FixedSizeList as List } from 'react-window';
First, import the necessary hooks from TanStack Table and the FixedSizeList component from react-window for virtualization.
const VirtualizedTable = ({ columns, data }) => {
  const { getTableProps, getTableBodyProps, headerGroups, rows, prepareRow } = useTable({
    columns,
    data
  });

  const RenderRow = React.useCallback(({ index, style }) => {
    const row = rows[index];
    prepareRow(row);
    return (
      <div {...row.getRowProps({ style })} className="tr">
        {row.cells.map(cell => {
          return <div {...cell.getCellProps()} className="td">
            {cell.render('Cell')}
          </div>
        })}
      </div>
    );
  }, [prepareRow, rows]);

  return (
    <div {...getTableProps()}>
      <div>
        {headerGroups.map(headerGroup => (
          <div {...headerGroup.getHeaderGroupProps()} className="tr">
            {headerGroup.headers.map(column => (
              <div {...column.getHeaderProps()} className="th">
                {column.render('Header')}
              </div>
            ))}
          </div>
        ))}
      </div>
      <List
        height={400}
        itemCount={rows.length}
        itemSize={35}
        width={1000}
      >
        {RenderRow}
      </List>
    </div>
  );
}
This code snippet showcases how to create a virtualized table using TanStack Table and react-window. It creates a functional component 'VirtualizedTable' that takes columns and data props. The useTable hook from TanStack Table initializes the table state. 'RenderRow' is a memoized function that renders each row based on the virtualized list index and style for efficient rendering. Finally, the FixedSizeList component from react-window renders only the visible rows based on scroll position, significantly improving performance with large datasets.