onclick hold react 1

onclick hold react

import { useState, useEffect, useCallback } from 'react';

export default function useLongPress(callback = () => {}, ms = 300) {
  const [startLongPress, setStartLongPress] = useState(false);

  useEffect(() => {
    let timerId;
    if (startLongPress) {
      timerId = setTimeout(callback, ms);
    } else {
      clearTimeout(timerId);
    }

    return () => {
      clearTimeout(timerId);
    };
  }, [callback, ms, startLongPress]);

  const start = useCallback(() => {
    setStartLongPress(true);
  }, []);
  const stop = useCallback(() => {
    setStartLongPress(false);
  }, []);

  return {
    onMouseDown: start,
    onMouseUp: stop,
    onMouseLeave: stop,
    onTouchStart: start,
    onTouchEnd: stop,
  };
}

Here is what the above code is Doing:
1. We have a useLongPress hook that takes a callback function and a time in milliseconds as arguments.
2. We have a startLongPress state variable that is set to false by default.
3. We have a useEffect hook that sets a timer when startLongPress is true.
4. We have a start and stop functions that set startLongPress to true and false respectively.
5. We return an object with onMouseDown, onMouseUp, onMouseLeave, onTouchStart, and onTouchEnd properties.

Now, let’s use this hook in our component:

Similar Posts