useSearch React hook

Created: 2021-04-17 - Last updated: 2021-04-24

easily search through an array with this hook. With great TypeScript support.

import * as React from "react";

export function useSearch<T = object>(key: keyof T, items: T[]) {
  const [search, setSearch] = React.useState("");
  const [filtered, setFiltered] = React.useState<T[]>(items);

  // if the 'items' change, make sure we update our state.
  React.useEffect(() => {
    setFiltered(items);
  }, [items]);

  function onChange(e: React.ChangeEvent<HTMLInputElement>) {
    const value = e.target.value;
    setSearch(value);

    // if there's no hits found, set filtered back to all items
    if (value.length <= 0) {
      setFiltered(items);

      // else, search on the provided 'key'
    } else {
      setFiltered(
        items.filter((v) =>
          ((v[key] as unknown) as string).toString().toLowerCase().includes(value.toLowerCase()),
        ),
      );
    }
  }

  return {
    search,
    onChange,
    filtered,
  };
}

See an example here 🚀

You can now also use this hook via npm/yarn by installing my npm package:

npm install @casper124578/useful

Later in your project

import { useSearch } from "@casper124578/useful/hooks/useSearch";