Creating a Custom Filter Hook for Table Data

Example of how to create and use a custom filter hook to add a search functionality that filters through table data.
import { useMemo } from 'react';

export function useFilteredData(data, searchQuery) {
  return useMemo(() => {
    if (!searchQuery) return data;
    return data.filter(item =>
      Object.values(item).some(value =>
  }, [data, searchQuery]);
This code creates a custom hook called useFilteredData, which filters the data based on a search query. It uses useMemo to optimize performance by memoizing the result, only recalculating the filtered data when data or searchQuery changes.
import React, { useState } from 'react';
import { useFilteredData } from './useFilteredData'; // Assuming the hook is saved in useFilteredData.js

const TableComponent = ({ initialData }) => {
  const [searchQuery, setSearchQuery] = useState('');
  const filteredData = useFilteredData(initialData, searchQuery);

  return (
      <input type='text' value={searchQuery} onChange={(e) => setSearchQuery(} />
        {/* Table rendering logic using filteredData */}

export default TableComponent;
This code shows how to use the custom hook in a functional React component to filter table data. It includes a search input that updates the searchQuery state. The useFilteredData hook is then called with the initial data and the search query to obtain filtered data, which is used to render the table.