Blog>
Snippets

Optimizing Sort Performance with useMemo Hook

Illustrate using the useMemo hook to memoize sorted data, preventing unnecessary re-renders and optimizing performance in React TanStack Table.
import { useMemo } from 'react';
First, import the useMemo hook from React.
const sortedData = useMemo(() => {
  return originalData.sort((a, b) => {
    // Comparison logic here
    return a.value - b.value;
  });
}, [originalData]);
Use the useMemo hook to memoize the sorted data. The sorting function is defined inside useMemo and will only re-execute when originalData changes. This prevents unnecessary re-renders and optimizes performance.
const tableInstance = useReactTable({
  data: sortedData,
  // other table options
});
Finally, use the memoized sortedData for your table instance with TanStack Table. This ensures that the table only re-renders when the data actually changes.