Blog>
Snippets

Custom Hooks for TanStack Table

Outline the creation of a custom hook to enhance the functionality of TanStack Table, such as integrating search or filtering features.
import { useFilters, useGlobalFilter } from '@tanstack/react-table';

// Custom Hook for global search functionality
export function useGlobalSearch(columns, data) {
    const filterTypes = React.useMemo(() => ({
        // Define a custom filter function for global search
        globalFilter: (rows, columnIds, filterValue) => {
            return rows.filter(row => {
                // Convert row values and filter value to lowercase for case-insensitive match
                return columnIds.some(id => {
                    return row.values[id].toString().toLowerCase().includes(filterValue.toLowerCase());
                });
            });
        }
    }), []);

    const globalFilter = useGlobalFilter(columns, data, {
        filterTypes,
    });

    return {
        ...globalFilter
    };
}
This custom hook, useGlobalSearch, utilizes useGlobalFilter from '@tanstack/react-table' to add global search functionality. It defines a custom global filter function that filters through all columns of the table. This function is case-insensitive, making it more flexible for user input. The filterTypes memo ensures that the filter function is not recreated on every render, enhancing performance.
import { useAsyncDebounce } from '@tanstack/react-table';

// Custom hook for debounced search field
export function useDebouncedSearchInput(value, onChange) {
    // State and setters for debounced value
    const [debouncedValue, setDebouncedValue] = React.useState(value);

    // Debounce callback
    const debouncedOnChange = useAsyncDebounce(value => {
        setDebouncedValue(value);
        onChange(value);
    }, 200); // 200ms delay

    return {
        debouncedValue,
        debouncedOnChange,
    };
}
This hook, useDebouncedSearchInput, is designed to debounce user input for search operations. It leverages useAsyncDebounce from '@tanstack/react-table', providing a mechanism to delay the execution of the search filter until 200ms after the user has stopped typing. This improves the application's performance by reducing the number of times the search operation is triggered.