useLongPressLoading saved progress…

useLongPress

A long-press — hold a button for a moment to trigger a secondary action — is everywhere on touch UIs: press-and-hold to preview, to enter selection mode, to show a context menu. The gesture is "the pointer stayed down for at least N milliseconds without leaving." useLongPress implements it as a timer: start counting on press, fire the callback if the timer completes, and cancel the moment the pointer lifts or leaves early.

Implement useLongPress(callback, { delay = 400 }). Return an object of event handlers — onMouseDown, onMouseUp, onMouseLeave, onTouchStart, onTouchEnd — that you spread onto an element. A press starts the timer; reaching delay fires callback(event); an early release or leave cancels it.

Signature

function useLongPress(callback, { delay = 400 }) {
  // returns { onMouseDown, onMouseUp, onMouseLeave, onTouchStart, onTouchEnd }
}

Examples

const handlers = useLongPress(() => openContextMenu(), { delay: 500 });
<button {...handlers}>Hold me</button>
// held 500ms -> menu opens; released at 300ms -> nothing
const bind = useLongPress((e) => select(e), { delay: 400 });
<Card {...bind} />; // press-and-hold to enter selection mode

Notes

  • Timer per pressonMouseDown/onTouchStart schedule a setTimeout(delay); the timeout firing calls callback.
  • Cancel on early exitonMouseUp, onMouseLeave, and onTouchEnd clear the pending timer so a quick tap doesn't trigger.
  • Fire once — a completed press fires exactly one callback; the timer isn't rescheduled until the next press.
  • Keep the timer id in a ref — it must survive renders and be reachable from both start and cancel; store it in a useRef.
Loading editor…