Membuat debounce function
Ridho C Pamungkas
Posted on September 9, 2022
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;
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;
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;
đź’– đź’Ş đź™… đźš©
Ridho C Pamungkas
Posted on September 9, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
programming How to visualize bar chart with react-chart-2, showing label on the bar
November 28, 2024
webdev 🚀 Introducing Folio-Motion: A Stunning Developer Portfolio Template! 🎨
November 28, 2024