UNPKG

@react-awesome/use-debounce

Version:

useDebounce debounces the state value.

22 lines (21 loc) 490 B
import { useState, useRef, useEffect } from "react"; function useDebounce(state, timeout = 300) { const [debounced, setDebounced] = useState(); const timeoutId = useRef(); useEffect(() => { const id = timeoutId.current; if (id) { clearTimeout(id); } timeoutId.current = window.setTimeout(() => { setDebounced(state); }, timeout); return () => { clearTimeout(id); }; }, [state, timeout]); return debounced; } export { useDebounce };