useLongPress

A React hook for handling long press gestures on elements with customizable duration and callbacks. Supports both mouse and touch events with TypeScript type safety.

Interactive Demo

Long press count: 0

Implementation

interface UseLongPressOptions {
  delay?: number;
  onStart?: () => void;
  onFinish?: () => void;
  onCancel?: () => void;
}

export function useLongPress(options: UseLongPressOptions = {}) {
  const { delay = 400, onStart, onFinish, onCancel } = options;
  const [isPressed, setIsPressed] = useState(false);
  const timeoutRef = useRef<NodeJS.Timeout>(null);

  const start = useCallback(() => {
    onStart?.();
    setIsPressed(true);
    timeoutRef.current = setTimeout(() => {
      onFinish?.();
      setIsPressed(false);
    }, delay);
  }, [delay, onStart, onFinish]);

  const cancel = useCallback(() => {
    if (timeoutRef.current) {
      clearTimeout(timeoutRef.current);
      onCancel?.();
      setIsPressed(false);
    }
  }, [onCancel]);

  const handlers = {
    onMouseDown: start,
    onMouseUp: cancel,
    onMouseLeave: cancel,
    onTouchStart: start,
    onTouchEnd: cancel,
  };

  return { isPressed, handlers };
}

Usage Examples

import { useLongPress } from '@/components/hooks/useLongPress';

function LongPressExample() {
  const { isPressed, handlers } = useLongPress({
    delay: 1000,
    onStart: () => console.log('Started pressing'),
    onFinish: () => console.log('Long press completed'),
    onCancel: () => console.log('Press cancelled'),
  });

  return (
    <button
      {...handlers}
      className={isPressed ? 'active' : ''}
    >
      Press and Hold
    </button>
  );
}

Documentation

Key Features

  • Customizable press duration
  • Support for both mouse and touch events
  • Callback functions for press start, finish, and cancel
  • Real-time press state tracking
  • TypeScript support
  • Automatic cleanup of timeouts

Common Use Cases

  • Context menu alternatives
  • Delete confirmations
  • Gaming controls
  • Mobile-friendly interactions
  • Custom gesture controls

API Reference

useLongPress(options: UseLongPressOptions)

Returns an object containing the press state and event handlers.

Options:

  • delay?: number (default: 400ms)
  • onStart?: () => void
  • onFinish?: () => void
  • onCancel?: () => void

Returns:

  • isPressed: boolean
  • handlers: Event handlers object

Browser Compatibility

The hook uses standard mouse and touch events, which are supported in all modern browsers. For touch events, ensure your target platform supports touch interactions.

useLongPress Hook - React Long Press Gesture Handler