Last active
March 24, 2020 13:32
-
-
Save cecigarcia/94e3fd1ab23a9b3dae6f02c453a447eb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useEffect, useRef } from "react"; | |
const noop = () => {}; | |
const useCancelableScheduledWork = () => { | |
const cancelCallback = useRef(noop); | |
const registerCancel = fn => (cancelCallback.current = fn); | |
const cancelScheduledWork = () => cancelCallback.current(); | |
// Cancels the current sheduled work before the "unmount" | |
useEffect(() => { | |
return cancelScheduledWork; | |
}, []); | |
return [registerCancel, cancelScheduledWork]; | |
}; | |
const useClickPrevention = ({ onClick, onDoubleClick, delay = 300 }) => { | |
const [registerCancel, cancelScheduledRaf] = useCancelableScheduledWork(); | |
const handleClick = () => { | |
cancelScheduledRaf(); | |
requestTimeout(onClick, delay, registerCancel); | |
}; | |
const handleDoubleClick = () => { | |
cancelScheduledRaf(); | |
onDoubleClick(); | |
}; | |
return [handleClick, handleDoubleClick]; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment