Rooks
HooksEvent Handling

useOnLongPress

Calls a callback after an element remains pressed for a duration.

About

useOnLongPress starts a timer for mouse or touch presses. useOnLongPressRef is a supported alias of the same implementation.

Example

import { useState } from "react";
import { useOnLongPress } from "rooks";

export default function PressStatus() {
  const [longPresses, setLongPresses] = useState(0);
  const [releases, setReleases] = useState(0);
  const longPressRef = useOnLongPress(
    () => setLongPresses((count) => count + 1),
    {
      duration: 300,
      onClick: () => setReleases((count) => count + 1),
    }
  );

  return (
    <button ref={longPressRef}>
      Long presses: {longPresses}; releases: {releases}
    </button>
  );
}

Parameters

  • callback: called when the press remains active for the full duration.
  • options.duration: delay in milliseconds; defaults to 300.
  • options.onClick(event): optional release callback receiving a native MouseEvent | TouchEvent.

The option type is private and is shown inline rather than exported from the package.

Return value

The hook returns a callback ref that accepts an HTMLElement | null.

Behavior and lifecycle

mousedown and touchstart begin the timer. mouseup, mouseleave, touchend, and touchcancel stop it and invoke onClick. That release callback also runs after a completed long press and on leave or cancellation; it is not limited to short clicks. Timer and event listeners are cleaned up when the target changes or the component unmounts.

Compatibility and accessibility

The native listeners do not implement keyboard long-press behavior. Use a semantic control and provide an equivalent click or keyboard action. Touch devices can synthesize mouse events after touch events, so make callbacks safe if the platform reports both sequences.

On this page