typescriptintermediate

useLongPress Hook

Detects long press gestures on touch and mouse devices with configurable threshold.

typescript
import { useRef, useCallback } from 'react';

interface LongPressOptions {
  threshold?: number;
  onLongPress: () => void;
  onClick?: () => void;
}

export function useLongPress({ threshold = 500, onLongPress, onClick }: LongPressOptions) {
  const timerRef = useRef<ReturnType<typeof setTimeout>>();
  const isLongPress = useRef(false);

  const start = useCallback(() => {
    isLongPress.current = false;
    timerRef.current = setTimeout(() => {
      isLongPress.current = true;
      onLongPress();
    }, threshold);
  }, [threshold, onLongPress]);

  const stop = useCallback(() => {
    clearTimeout(timerRef.current);
    if (!isLongPress.current && onClick) onClick();
  }, [onClick]);

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

Use Cases

  • Context menus
  • Mobile interactions

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.