codedsaif-react-hooks
Version:
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
36 lines (33 loc) • 1.14 kB
JavaScript
import { useState, useEffect } from "react";
/**
* Custom hook to debounce a value after a specified delay.
* @param {*} value - The value to debounce.
* @param {number} [delay=500] - Delay in milliseconds before updating the debounced value.
* @returns {*} - The debounced value.
* @example
* const [searchTerm, setSearchTerm] = useState("");
* const debouncedSearch = useDebounce(searchTerm, 300);
* useEffect(() => {
* if (debouncedSearch) {
* fetch(`https://api.example.com/search?q=${debouncedSearch}`)
* .then((res) => res.json())
* .then((data) => console.log(data));
* }
* }, [debouncedSearch]);
* return (
* <input
* type="text"
* placeholder="Search..."
* onChange={(e) => setSearchTerm(e.target.value)}
* />
* );
*/
function useDebounce(value, delay = 500) {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
const handler = setTimeout(() => setDebouncedValue(value), delay);
return () => clearTimeout(handler);
}, [value, delay]);
return debouncedValue;
}
export default useDebounce;