Skip to content

Instantly share code, notes, and snippets.

@jwrigh26
Created September 24, 2019 17:56
Show Gist options
  • Save jwrigh26/608b3cb4e6d1d233f4108785bba78d0b to your computer and use it in GitHub Desktop.
Save jwrigh26/608b3cb4e6d1d233f4108785bba78d0b to your computer and use it in GitHub Desktop.
React gist for a custom hook: useLongPress
import {useState, useEffect, useCallback} from 'react';
export function useLongPress(callback = () => {}, ms = 400) {
const [startLongPress, setStartLongPress] = useState(false);
useEffect(() => {
let timerId;
if (startLongPress) {
timerId = setTimeout(callback, ms);
} else {
clearTimeout(timerId);
}
return () => {
clearTimeout(timerId);
};
}, [startLongPress]);
const start = useCallback(() => {
setStartLongPress(true);
}, []);
const stop = useCallback(() => {
setStartLongPress(false);
}, []);
return {
onMouseDown: start,
onMouseUp: stop,
onMouseLeave: stop,
onTouchStart: () => start,
onTouchEnd: () => stop,
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment