ShakibDShy

Hooks

A beginner's guide to using hooks in React Table Grid

React Table Grid Hooks

React Table Grid provides several custom hooks to help you build powerful tables. Think of hooks as special functions that let you add extra features to your tables. Let's explore each hook and learn how to use them!

Table of Contents

  1. useTableGrid - The Main Hook
  2. useTableState - For Managing Table State
  3. useVirtualization - For Large Data Sets
  4. useTableEvents - For Handling Interactions

useTableGrid

This is the main hook you'll use to create tables. It handles everything from sorting to filtering!

Basic Usage

Here's a simple example to get you started:

import { useTableGrid } from '@shakibdshy/react-tablegrid';
 
function SimpleTable() {
  // Define your data
  const data = [
    { id: 1, name: 'John', age: 25 },
    { id: 2, name: 'Jane', age: 30 },
  ];
 
  // Define your columns
  const columns = [
    { id: 'name', header: 'Name', accessorKey: 'name' },
    { id: 'age', header: 'Age', accessorKey: 'age' },
  ];
 
  // Use the hook
  const tableInstance = useTableGrid({
    data,
    columns,
  });
 
  // Render your table
  return <TableGrid {...tableInstance} />;
}

Adding Features

Want to add sorting or filtering? It's easy!

function TableWithFeatures() {
  const tableInstance = useTableGrid({
    data,
    columns,
    // Start with sorted data
    initialState: {
      sortColumn: 'name',
      sortDirection: 'asc',
    },
    // Track changes
    onStateChange: (state) => {
      console.log('Table changed:', state);
    },
  });
 
  return <TableGrid {...tableInstance} />;
}

What You Get

The useTableGrid hook gives you lots of useful tools:

const {
  // Your data
  data,              // Current table data
  filteredData,      // Data after filtering/sorting
  
  // Sorting
  sortColumn,        // Current sort column
  sortDirection,     // Current sort direction ('asc' or 'desc')
  handleSort,        // Function to sort columns
  
  // Filtering
  filterValue,       // Current search/filter text
  setFilterValue,    // Function to update filter
  
  // Column features
  visibleColumns,    // Currently visible columns
  toggleColumnVisibility, // Show/hide columns
  
  // And more!
} = useTableGrid({ /* options */ });

useTableState

This hook helps you manage the state of your table independently. It's perfect when you want to control sorting, filtering, or pagination yourself!

Basic Usage

import { useTableState } from '@shakibdshy/react-tablegrid';
 
function TableWithState() {
  // Initialize table state
  const {
    state,
    setState,
    // Helper functions
    setSorting,
    setFiltering,
    setColumnVisibility,
  } = useTableState({
    // Initial state values
    initialState: {
      sortColumn: 'name',
      sortDirection: 'asc',
      filterValue: '',
      visibleColumns: ['name', 'age', 'email'],
    },
  });
 
  return (
    <div>
      {/* Custom filter input */}
      <input
        type="text"
        value={state.filterValue}
        onChange={(e) => setFiltering(e.target.value)}
        placeholder="Search..."
      />
 
      {/* Table with controlled state */}
      <TableGrid
        columns={columns}
        data={data}
        state={state}
        onStateChange={setState}
      />
    </div>
  );
}

What You Can Control

The useTableState hook lets you manage:

const {
  // Current state
  state: {
    sortColumn,        // Which column is being sorted
    sortDirection,     // Sort direction ('asc' or 'desc')
    filterValue,       // Current search text
    visibleColumns,    // Which columns are shown
    pinnedColumns,     // Which columns are pinned
  },
 
  // Update functions
  setState,           // Update the whole state
  setSorting,         // Update sort settings
  setFiltering,       // Update search filter
  setColumnVisibility,// Show/hide columns
  setPinnedColumns,   // Pin/unpin columns
  resetState,         // Reset to initial state
} = useTableState({ /* options */ });

Common Use Cases

  1. Custom Sorting Controls
function TableWithCustomSort() {
  const { state, setSorting } = useTableState();
 
  return (
    <div>
      <select
        value={state.sortColumn}
        onChange={(e) => setSorting(e.target.value, state.sortDirection)}
      >
        <option value="name">Sort by Name</option>
        <option value="age">Sort by Age</option>
      </select>
 
      <TableGrid
        columns={columns}
        data={data}
        state={state}
      />
    </div>
  );
}
  1. Custom Filter UI
function TableWithCustomFilter() {
  const { state, setFiltering } = useTableState();
 
  return (
    <div>
      <div className="search-box">
        <input
          type="text"
          value={state.filterValue}
          onChange={(e) => setFiltering(e.target.value)}
          placeholder="Search..."
        />
        <button onClick={() => setFiltering('')}>
          Clear
        </button>
      </div>
 
      <TableGrid
        columns={columns}
        data={data}
        state={state}
      />
    </div>
  );
}

Best Practices

  1. Initialize with Default Values

    const { state } = useTableState({
      initialState: {
        sortColumn: 'name',
        sortDirection: 'asc',
        filterValue: '',
        visibleColumns: ['name', 'age', 'email'],
      },
    });
  2. Handle State Changes

    const { state, setState } = useTableState({
      onStateChange: (newState) => {
        console.log('State changed:', newState);
        // Save to localStorage, update URL, etc.
      },
    });
  3. Reset When Needed

    const { resetState } = useTableState();
     
    // Add a reset button
    <button onClick={resetState}>
      Reset Table
    </button>

useVirtualization

When you have lots of data (hundreds or thousands of rows), this hook helps your table load faster by only showing what's visible.

Simple Example

import { useVirtualization } from '@shakibdshy/react-tablegrid';
 
function FastTable() {
  // Your data array with many items
  const data = Array.from({ length: 1000 }, (_, index) => ({
    id: index + 1,
    name: `Item ${index + 1}`,
  }));
 
  // Use virtualization
  const {
    containerRef,    // Attach this to your container
    virtualItems,    // Only the visible items
    totalHeight,     // Total scroll height
  } = useVirtualization(data, {
    enabled: true,   // Turn on virtualization
    rowHeight: 48,   // Height of each row
    overscan: 5,     // Extra rows to render
  });
 
  return (
    <div 
      ref={containerRef} 
      style={{ height: '500px', overflow: 'auto' }}
    >
      <div style={{ height: totalHeight }}>
        {virtualItems.map(virtualRow => (
          <div key={virtualRow.index} style={virtualRow.style}>
            Row {virtualRow.index + 1}
          </div>
        ))}
      </div>
    </div>
  );
}

Options You Can Use

  • enabled: Turn virtualization on/off
  • rowHeight: How tall each row should be
  • overscan: Extra rows to load (for smooth scrolling)
  • scrollingDelay: Time to wait before updating (for performance)
  • onEndReached: Function to call when user reaches the bottom

useTableEvents

This hook helps you handle all the interactions with your table, like clicking, sorting, or filtering.

Basic Example

import { useTableEvents } from '@shakibdshy/react-tablegrid';
 
function InteractiveTable() {
  const {
    handleSort,      // For sorting columns
    handleFilterChange, // For filtering
    handleRowSelect, // For selecting rows
  } = useTableEvents({
    state,           // Current table state
    updateState,     // Function to update state
    events: {
      // What to do when things happen
      onSort: (column, direction) => {
        console.log(`Sorting ${column.id} ${direction}`);
      },
      onFilter: (value) => {
        console.log(`Searching for: ${value}`);
      },
    },
  });
 
  return (
    <TableGrid
      onSort={handleSort}
      onFilterChange={handleFilterChange}
      onRowSelect={handleRowSelect}
      // ... other props
    />
  );
}

Available Events

You can handle many different events:

  • Sorting columns
  • Filtering data
  • Selecting rows
  • Resizing columns
  • Showing/hiding columns
  • Pinning columns
  • Keyboard navigation

Tips for Beginners

  1. Start Simple

    • Begin with just useTableGrid
    • Add features one at a time
    • Test each feature as you add it
  2. Common Patterns

    // Basic table setup
    function MyTable() {
      const table = useTableGrid({
        data,
        columns,
      });
      return <TableGrid {...table} />;
    }
     
    // Table with sorting
    function SortableTable() {
      const table = useTableGrid({
        data,
        columns,
        initialState: { sortColumn: 'name' },
      });
      return <TableGrid {...table} />;
    }
     
    // Table with search
    function SearchableTable() {
      const table = useTableGrid({
        data,
        columns,
        enableFiltering: true,
      });
      return <TableGrid {...table} />;
    }
  3. Debugging Tips

    • Use console.log to see what's happening
    • Check the state changes in onStateChange
    • Look at the filtered data to debug search issues

Next Steps

  • Try building a simple table with useTableGrid
  • Add sorting and filtering
  • Experiment with column visibility
  • For big tables, try useVirtualization
  • Add interactivity with useTableEvents

Remember:

You don't need to use all features at once. Start with what you need and add more as your table grows!

Hook Configurations

useTableGrid Options

interface UseTableGridOptions<T> {
  data: T[];                      // Table data
  columns: Column<T>[];           // Column definitions
  initialState?: Partial<TableState<T>>; // Initial state
  onStateChange?: (state: TableState<T>) => void; // State change handler
  events?: Partial<TableEventMap<T>>; // Event handlers
  columnResizeMode?: "onChange" | "onResize"; // Resize behavior
  columnResizeDirection?: "ltr" | "rtl"; // Resize direction
  debounceMs?: number;           // Debounce delay
  isLoading?: boolean;           // Loading state
  serverSide?: ServerSideConfig<T>; // Server-side options
}

useVirtualization Options

interface VirtualizationConfig {
  enabled: boolean;              // Enable virtualization
  rowHeight: number;            // Height of each row
  overscan: number;             // Extra rows to render
  scrollingDelay?: number;      // Scroll update delay
  onEndReached?: () => void;    // End of list callback
}

Last updated on