Row Virtualization Example
Material React Table has a built-in row virtualization feature (via @tanstack/react-virtual
) that allows you to render a large number of rows without major performance issues that you would normally see with a large number of DOM elements.
Try out the performance of the table below with 10,000 rows! Filtering, Search, and Sorting also maintain usable performance.
Be sure to also check out the full virtualization feature guide docs to learn about both Row and Column Virtualization.
NOTE: You should only enable row virtualization if you have a large number of rows or columns. Depending on the size of the table, if you are rendering fewer than a couple dozen rows at a time, you will actually just be adding extra overhead to the table renders. Virtualization only becomes necessary when you have over 50 rows or so at the same time with no pagination or dozens of columns.
# | First Name | Middle Name | Last Name | Email Address | Address | Zip Code | City | State | Country |
---|
1import { useEffect, useMemo, useRef, useState } from 'react';2import {3 MaterialReactTable,4 useMaterialReactTable,5 type MRT_ColumnDef,6 type MRT_SortingState,7 type MRT_Virtualizer,8} from 'material-react-table';9import { makeData, type Person } from './makeData';1011const Example = () => {12 const columns = useMemo<MRT_ColumnDef<Person>[]>(13 //column definitions...58 );5960 //optionally access the underlying virtualizer instance61 const rowVirtualizerInstanceRef =62 useRef<MRT_Virtualizer<HTMLDivElement, HTMLTableRowElement>>(null);6364 const [data, setData] = useState<Person[]>([]);65 const [isLoading, setIsLoading] = useState(true);66 const [sorting, setSorting] = useState<MRT_SortingState>([]);6768 useEffect(() => {69 if (typeof window !== 'undefined') {70 setData(makeData(10_000));71 setIsLoading(false);72 }73 }, []);7475 useEffect(() => {76 //scroll to the top of the table when the sorting changes77 try {78 rowVirtualizerInstanceRef.current?.scrollToIndex?.(0);79 } catch (error) {80 console.error(error);81 }82 }, [sorting]);8384 const table = useMaterialReactTable({85 columns,86 data, //10,000 rows87 enableBottomToolbar: false,88 enableGlobalFilterModes: true,89 enablePagination: false,90 enableRowNumbers: true,91 enableRowVirtualization: true,92 muiTableContainerProps: { sx: { maxHeight: '600px' } },93 onSortingChange: setSorting,94 state: { isLoading, sorting },95 rowVirtualizerInstanceRef, //optional96 rowVirtualizerOptions: { overscan: 5 }, //optionally customize the row virtualizer97 });9899 return <MaterialReactTable table={table} />;100};101102export default Example;103
View Extra Storybook Examples