useToggleuseToggle+useEventRefuseSafeEffectuseEventControluseDebounceuseThrottleuseClickOutsideuseTabsuseDateuseDatesuseImageuseCaptureuseIntersectionObserver
react react-hook ironman30

useDebounce

To delay a event until no further request.


LINKS

鐵人賽連結


function useDebounce(cb, delay, deps) {
  const initRef = useRef(true)
  const [isPending, setIsPending] = useState(false)

  useEffect(() => {
    if (initRef.current) {
      initRef.current = false
      return
    }

    setIsPending(true)
    const timeout = setTimeout(() => {
      cb()
      setIsPending(false)
    }, delay)

    return () => clearTimeout(timeout)
  }, deps)

  return isPending
}

Params

name type description
cbfunction

callback function to fire depends on setTimeout

delaynumberms (unit), default as 250ms
depsarraysame as useEffect deps

Return

name type description
isPendingboolean

Example

input

delayInput

choose

setTimeout

idle


Regular Version (no debounce)