Blog>
Snippets

Performance Optimization with useMemo for Filtering

Demonstrate how to use the useMemo hook to optimize performance by memoizing the filter results in React TanStack Table, ensuring filtering computations are not unnecessarily repeated.
import React, { useMemo } from 'react';
import { useReactTable, getCoreRowModel } from '@tanstack/react-table';
Initial import statements including React, useReactTable hook from TanStack Table, and useMemo from React for optimizing performance.
const TableComponent = ({ columns, data }) => {
  const [globalFilter, setGlobalFilter] = React.useState('');
Setting up the TableComponent function component with its state for global filtering.
const filteredData = useMemo(() => {
    return data.filter(row => {
      return columns.some(column => {
        return String(row[column.accessor] || '').toLowerCase().includes(globalFilter.toLowerCase());
      });
    });
  }, [data, columns, globalFilter]);
Using the useMemo hook to memoize the filtered data. This avoids unnecessary computations on every render when the data, columns, or globalFilter has not changed.
const tableInstance = useReactTable({
    data: filteredData,
    columns,
    getCoreRowModel: getCoreRowModel(),
    state: {
      globalFilter,
    },
    onGlobalFilterChange: setGlobalFilter,
  });
Creating a table instance with useReactTable hook using the memoized filtered data.
return (
    // JSX to render the table goes here
  );
};
Rendering the table component with the table instance data.