useToggleuseToggle+useEventRefuseSafeEffectuseEventControluseDebounceuseThrottleuseClickOutsideuseTabsuseDateuseDatesuseImageuseCaptureuseIntersectionObserver
react react-hook ironman30

useEventControl

A cancellable event(request) with hook (similar to debounce).


LINKS

鐵人賽連結


const [startEvent, isPending, cancelEvent] = useEventControl(cb, delay)

Params

name type description
cbfunctionAfter the startEvent function been call, callback will be fired after the setTimeout timer expires.
delaynumberms (unit), default as 2000ms

Return

name type description
startEventfunctionTo start the event, will trigger setTimeout timer to count down.
isPendingboolean
cancelEventfunctionTo cancel the event.

function useEventControl(cb, delay = 2000) {
  const timeoutRef = useRef(null)
  const [isPending, setIsPending] = useState(false)
  const argsRef = useRef(null)

  const startEvent = useCallback((...args) => {
    if (timeoutRef.current) {
      clearTimeout(timeoutRef.current)
    }
    argsRef.current = args
    setIsPending(true)
  }, [])

  const cancelEvent = useCallback(() => {
    if (timeoutRef.current) {
      clearTimeout(timeoutRef.current)
    }
    setIsPending(false)
  }, [])

  useEffect(() => {
    if (isPending) {
      timeoutRef.current = setTimeout(() => {
        cb(...argsRef.current)
        setIsPending(false)
      }, delay)
    }

    return () => clearTimeout(timeoutRef.current)
  }, [isPending])

  return [startEvent, isPending, cancelEvent]
}

Example