Skip to content

Instantly share code, notes, and snippets.

@cecigarcia
Last active March 24, 2020 13:32
Show Gist options
  • Save cecigarcia/94e3fd1ab23a9b3dae6f02c453a447eb to your computer and use it in GitHub Desktop.
Save cecigarcia/94e3fd1ab23a9b3dae6f02c453a447eb to your computer and use it in GitHub Desktop.
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