Blog>
Snippets

Integrating React-Window with TanStack Table for Row Virtualization

Show the process of integrating the react-window library with React TanStack Table to efficiently render a large list of row data by virtualizing rows.
import { useTable, useBlockLayout } from 'react-table';
import { FixedSizeList as List } from 'react-window';
Import necessary hooks from react-table for table logic and layout. Import FixedSizeList from react-window for virtualization.
const RenderRow = React.memo(({ index, style, data }) => {
  const row = data.rows[index];
  data.prepareRow(row);
  return (
    <div {...row.getRowProps({ style })} className="tr">
      {row.cells.map(cell => (
        <div {...cell.getCellProps()} className="td">
          {cell.render('Cell')}
        </div>
      ))}
    </div>
  );
});
Define the RenderRow component, which receives index and style from react-window, and data from the parent component. It prepares and renders a table row.
const VirtualizedTable = ({ columns, data }) => {
  const defaultColumn = React.useMemo(() => ({
    minWidth: 30,
    width: 150,
    maxWidth: 200,
  }), []);
  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    prepareRow,
    rows,
  } = useTable({
    columns,
    data,
    defaultColumn,
  },
  useBlockLayout);
  
  const RenderVirtualizedList = React.useMemo(() => (
    <List
      height={400}
      itemCount={rows.length}
      itemSize={35}
      width={'auto'}
      itemData={{ rows, prepareRow }}
    >
      {RenderRow}
    </List>
  ), [rows]);

  return (
    <div {...getTableProps()} className="table">
      <div>
        {// Table header rendering is omitted for brevity}
      </div>
      <div {...getTableBodyProps()}>
        {RenderVirtualizedList}
      </div>
    </div>
  );
}
VirtualizedTable component integrates react-table with react-window. It utilizes useTable and useBlockLayout from react-table for managing table state and layout. React-window's List is used to render only visible rows, improving performance with large datasets.