Blog>
Snippets

Debouncing Filter Input for Large Dataset in React TanStack Table

Example of implementing a debounce function for the global filter input to enhance performance and user experience when dealing with large datasets in React TanStack Table.
import { useState, useEffect } from 'react';
Importing useState and useEffect hooks from React.
import { useReactTable, getCoreRowModel, getFilteredRowModel, getPaginationRowModel } from '@tanstack/react-table';
Importing functions from @tanstack/react-table to manage table state, filtering and pagination.
function useDebounce(value, delay) {
    const [debouncedValue, setDebouncedValue] = useState(value);

    useEffect(() => {
        const handler = setTimeout(() => setDebouncedValue(value), delay);

        return () => clearTimeout(handler);
    }, [value, delay]);

    return debouncedValue;
}
Defining a custom hook to debounce values. This delays the update of the value state until after a specified delay, improving performance for operations like filtering on fast input.
const TableComponent = ({ data, columns }) => {
    const [globalFilter, setGlobalFilter] = useState('');
    const debouncedGlobalFilter = useDebounce(globalFilter, 300);

    const table = useReactTable({
        data,
        columns,
        state: { globalFilter: debouncedGlobalFilter },
        getCoreRowModel: getCoreRowModel(),
        getFilteredRowModel: getFilteredRowModel(),
        getPaginationRowModel: getPaginationRowModel(),
        onGlobalFilterChange: setGlobalFilter
    });

    return (
        <div>
            <input
                value={globalFilter}
                onChange={e => setGlobalFilter(e.target.value)}
                placeholder="Search all columns..."
            />
            {/* Render table UI using table instance */}
        </div>
    );
}
Creating a TableComponent that utilizes the useReactTable hook from @tanstack/react-table, and integrates the useDebounce hook to implement a debounced global filter. The input's onChange updates the globalFilter state, which is debounced before being applied to the table's global filter, effectively reducing the number of re-renders and enhancing performance.