Blog>
Snippets

Optimizing Performance for Dynamic Column Visibility

Showcase techniques for optimizing React TanStack Table's performance when handling dynamic column visibility, including memoization and lazy loading strategies.
const [visibleColumns, setVisibleColumns] = React.useState(initialVisibleColumns);
Initialize state for managing visible columns. 'initialVisibleColumns' should be an array of the IDs of the columns that are initially visible.
const memoizedColumnVisibility = React.useMemo(() => {
  return columns.map(column => ({
    ...column,
    isVisible: visibleColumns.includes(column.id)
  }));
}, [columns, visibleColumns]);
Use memoization to prevent unnecessary re-renders. This creates a new columns array only when 'columns' or 'visibleColumns' changes, enhancing performance.
const toggleColumnVisibility = (columnId) => {
  setVisibleColumns(currentVisibleColumns => {
    return currentVisibleColumns.includes(columnId)
      ? currentVisibleColumns.filter(id => id !== columnId)
      : [...currentVisibleColumns, columnId];
  });
};
Function to toggle the visibility of a column by its ID. It updates the 'visibleColumns' state, adding or removing the column ID based on its current visibility.