useLongPress.ts 825 B

123456789101112131415161718192021222324252627
  1. // https://stackoverflow.com/a/54749871/2760968
  2. import { useEffect, useState } from "react";
  3. export default function useLongPress(callback: () => void, ms = 300) {
  4. const [startLongPress, setStartLongPress] = useState(false);
  5. useEffect(() => {
  6. let timerId: NodeJS.Timeout;
  7. if (startLongPress) {
  8. timerId = setTimeout(callback, ms);
  9. } else {
  10. clearTimeout(timerId);
  11. }
  12. return () => {
  13. clearTimeout(timerId);
  14. };
  15. }, [callback, ms, startLongPress]);
  16. return {
  17. onMouseDown: () => setStartLongPress(true),
  18. onMouseUp: () => setStartLongPress(false),
  19. onMouseLeave: () => setStartLongPress(false),
  20. onTouchStart: () => setStartLongPress(true),
  21. onTouchEnd: () => setStartLongPress(false),
  22. };
  23. }