search in react

first use useState, useEffect and useRef hooks. Then use setTimeout and last use clean up function to clear the timer that we create using setTimeout.

import React, { useEffect, useRef, useState } from "react";

import Card from "../UI/Card";
import "./Search.css";

const Search = (props) => {
  const { onLoadHandler } = props;
  const [enteredValue, setenteredValue] = useState("");
  const inputRef = useRef();

  useEffect(() => {
    const timer = setTimeout(() => {
      if (enteredValue === inputRef.current.value) {
        const query =
          enteredValue === ""
            ? ""
            : `?orderBy="title"&equalTo="${enteredValue}"`;
        console.log("use effect");
        fetch(
          "https://simple-1db1e-default-rtdb.firebaseio.com/ings.json" + query
        )
          .then((response) => response.json())
          .then((responseData) => {
            onLoadHandler(responseData);
          });
      }
    }, 500);
    return ()=>{
      clearTimeout(timer)
    }
  }, [onLoadHandler, enteredValue, inputRef]);

  return (
    <section className="search">
      <Card>
        <div className="search-input">
          <label>Filter by Title</label>
          <input
            ref={inputRef}
            type="text"
            value={enteredValue}
            onChange={(e) => setenteredValue(e.target.value)}
          />
        </div>
      </Card>
    </section>
  );
};

export default Search;