Blog>
Snippets

Implementing Custom Hooks for Responsive TanStack Tables

Create a custom React hook that uses the 'useEffect' and 'useState' hooks to manage and update the state of table columns for responsiveness.
import { useEffect, useState } from 'react';
Imports useEffect and useState hooks from React.
import { useReactTable, createColumnHelper } from '@tanstack/react-table';
Imports useReactTable and createColumnHelper from '@tanstack/react-table' for table creation and column management.
const useResponsiveColumns = (defaultColumns) => {
  const [columns, setColumns] = useState(defaultColumns);
  
  useEffect(() => {
    const handleResize = () => {
      const isMobile = window.innerWidth < 768;
      const updatedColumns = defaultColumns.map(column => ({
        ...column,
        isHidden: isMobile && column.hideOnMobile
      })).filter(column => !column.isHidden);
      setColumns(updatedColumns);
    };
    
    window.addEventListener('resize', handleResize);
    handleResize();
    
    return () => window.removeEventListener('resize', handleResize);
  }, [defaultColumns]);
  
  return columns;
};
Defines a custom hook useResponsiveColumns that takes defaultColumns as input. It uses useEffect to listen to window resize events, adjusting the visibility of columns based on the viewport width, specifically hiding columns marked with hideOnMobile in mobile view. It returns the updated columns for responsive behavior.
const App = () => {
  // Define your columns with hideOnMobile indicator
  const defaultColumns = [
    { accessor: 'id', Header: 'ID' },
    { accessor: 'name', Header: 'Name' },
    { accessor: 'age', Header: 'Age', hideOnMobile: true }
  ];
  
  const columns = useResponsiveColumns(defaultColumns);
  const table = useReactTable({ columns, data: [] });
  
  return (/* Render your table with TanStack Table's hooks */);
};
Implements the App component where useResponsiveColumns is used along with useReactTable. It demonstrates defining a set of defaultColumns, some of which may be hidden on mobile devices using the hideOnMobile property. The columns are then made responsive with useResponsiveColumns, and used in the table instance created with useReactTable.