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 |
---|
cb | function | After the startEvent function been call, callback will be fired after the setTimeout timer expires. |
delay | number | ms (unit), default as 2000ms |
Return
name |
type |
description |
---|
startEvent | function | To start the event, will trigger setTimeout timer to count down. |
isPending | boolean | |
cancelEvent | function | To 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