showing results for - "onclick hold react"
Assya
24 Oct 2017
1import { useState, useEffect, useCallback } from 'react';
2
3export default function useLongPress(callback = () => {}, ms = 300) {
4  const [startLongPress, setStartLongPress] = useState(false);
5
6  useEffect(() => {
7    let timerId;
8    if (startLongPress) {
9      timerId = setTimeout(callback, ms);
10    } else {
11      clearTimeout(timerId);
12    }
13
14    return () => {
15      clearTimeout(timerId);
16    };
17  }, [callback, ms, startLongPress]);
18
19  const start = useCallback(() => {
20    setStartLongPress(true);
21  }, []);
22  const stop = useCallback(() => {
23    setStartLongPress(false);
24  }, []);
25
26  return {
27    onMouseDown: start,
28    onMouseUp: stop,
29    onMouseLeave: stop,
30    onTouchStart: start,
31    onTouchEnd: stop,
32  };
33}
34