Created
September 24, 2019 17:56
-
-
Save jwrigh26/608b3cb4e6d1d233f4108785bba78d0b to your computer and use it in GitHub Desktop.
React gist for a custom hook: useLongPress
This file contains hidden or 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 {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