useDebounce Hook ๐Ÿš€

Cagatay Unal - Mar 6 '23 - - Dev Community

I'll tell you about the use of Debounce Function as useDebounce Hook in React, which positively affects search request performance and which I also use frequently.

Firstly, let's create a react project in a simple way with the following command lines.



npx create-react-app my-app


Enter fullscreen mode Exit fullscreen mode

Then you can create and use useDebounce as in the code blocks below.

useDebounce.js



import { useState, useEffect } from "react";

const useDebounce = (val, delay) => {
    const [ debounceVal, setDebounceVal ] = useState(val);

    useEffect(() => {
        const handler = setTimeout(() => {
            setDebounceVal(val);
        }, delay);

        return () => {
            clearTimeout(handler);
        }
    }, [val]);

    return debounceVal;
}

export default useDebounce;


Enter fullscreen mode Exit fullscreen mode

App.js



import { useState, useEffect } from "react";
import useDebounce from "./useDebounce";

const DATA_LIST = [
  "Luke Skywalker",
  "C-3PO",
  "R2-D2",
  "Darth Vader",
  "Leia Organa",
  "Owen Lars",
  "Beru Whitesun lars",
  "R5-D4",
  "Biggs Darklighter",
  "Obi-Wan Kenobi",
];

function App() {
  const [results, setResults] = useState([]);
  const [text, setText] = useState("");

  const debounce = useDebounce(text, 500);

  useEffect(() => {
    const data = DATA_LIST.filter((el) => el.toLowerCase().includes(debounce));
    setResults(data);
  }, [debounce]);

  return (
    <div className="app">
      <h1>search</h1>
      <input
        type="text"
        value={text}
        onChange={(e) => setText(e.target.value)}
      />
      <div className="search-result">
        {results.length > 0 ? (
          results.map((item, i) => (
            <div key={i} className="result-item">
              {item}
            </div>
          ))
        ) : (
          <p>No Result</p>
        )}
      </div>
    </div>
  );
}

export default App;



Enter fullscreen mode Exit fullscreen mode

You can also review this example from my github repo: https://github.com/cagatay-unal/useDebounce-hook

Image description

. . . . .