DEV Community

Ridho C Pamungkas
Ridho C Pamungkas

Posted on

Membuat debounce function

Kasus dibawah ini melakukan efisiensi pada live search data, dengan menggunakan debounce function ini kita bisa mendebounce karakter yang diinput user yang berubah dengan cepat dan mengeksekusinya saat waktu yang kita tentukan. dengan melakukan ini kode tidak melakukan pencarian setiap karakter berubah, ini membuat lebih efisien dan tidak mengganggu performance saat melakukan request ke suatu API.

function useDebounce

import { useState, useEffect } from "react";

const useDebounce = (val: any, delay: number) => {
  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

Contoh sederhana

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

const listData = ["sabun", "minyak", "gula", "garam", "kopi"];

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

  const debounce = useDebounce(text, 500);

  useEffect(() => {
    const filterData = listData.filter((obj) =>
      obj.toLowerCase().includes(debounce)
    );
    setResults(filterData);
  }, [debounce]);

  return (
    <div className="App">
      <input
        type="text"
        value={text}
        onChange={(e) => setText(e.target.value)}
      />
      {results.length > 0 ? (
        results.map((el: string, i: number) => <div key={i}>{el}</div>)
      ) : (
        <div>no results</div>
      )}
    </div>
  );
}

export default App;

Enter fullscreen mode Exit fullscreen mode

Contoh menggunakan fetching data

import { useState } from "react";
import useDebounce from "./use-debounce";
import useFetch from "./use-fetch";


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

  const debounce = useDebounce(text, 500);
  const url = `http://www.omdbapi.com/?t=${debounce}`;
  const {data, isLoading, error} = useFetch(url);

  if(isLoading){
    return <div>loading...</div>
  }

  if(error) {
    return <div>{error}</div>
  }


  return (
    <div className="App">
      <input
        type="text"
        value={text}
        onChange={(e) => setText(e.target.value)}
      />
      {data.length > 0 ? (
        data.map((el: string, i: number) => <div key={i}>{el}</div>)
      ) : (
        <div>no results</div>
      )}
    </div>
  );
}

export default App;

Enter fullscreen mode Exit fullscreen mode

Top comments (0)