UNPKG

@ehsaneha/react-debounce

Version:

useDebounce is a custom React hook that delays invoking a function until a specified time has passed since the last call, ideal for handling user input like search fields.

34 lines (33 loc) 1.03 kB
import { useEffect, useRef } from "react"; /** * useDebounce * Calls the provided function after the user stops triggering it for `delay` ms. * * @param callback Function to run after debounce delay * @param delay Delay in ms * @returns A debounced version of the function */ export function useDebounce(callback, delay) { const timeoutRef = useRef(null); const savedCallback = useRef(callback); // Keep the latest callback reference useEffect(() => { savedCallback.current = callback; }, [callback]); function debouncedFunction(...args) { if (timeoutRef.current) { clearTimeout(timeoutRef.current); } timeoutRef.current = setTimeout(() => { savedCallback.current(...args); }, delay); } // Cleanup on unmount useEffect(() => { return () => { if (timeoutRef.current) clearTimeout(timeoutRef.current); }; }, []); return debouncedFunction; }