# useLongPress

Calls `onLongPress` when the user presses and holds an element, with mouse, touch, or pen. Returns event handlers to spread onto the element.

Cancels if the pointer is released, leaves, or moves past `moveTolerance` (so scrolling on a phone doesn't trigger it). Only the primary button counts. After a long press, the click that follows is swallowed, so the element's `onClick` doesn't also run, and the mobile context menu is suppressed while holding.

## Import

```ts
import { useLongPress } from '@vincent.ri/react-tils'
// or only this hook
import { useLongPress } from '@vincent.ri/react-tils/useLongPress'
```

## Usage

```ts
const longPress = useLongPress(() => setSelected(item.id))
return (
  <li {...longPress} onClick={() => open(item)}>
    {item.name}
  </li>
)
```

## When to use it

Secondary actions on touch devices, e.g. select an item in a list, show a preview, or "hold to delete".

## When not to

It is the only way to reach an action; long press is hard to discover and not keyboard accessible, so offer a button or menu too. Add CSS `user-select: none; -webkit-touch-callout: none` on the element to stop text selection on iOS.

## API

```ts
function useLongPress(onLongPress: (event: PointerEvent) => void, options?: LongPressOptions): LongPressHandlers
```

| Parameter | Description |
| --- | --- |
| `onLongPress` | Called with the original pointer event once the hold completes. |
| `options` | `delayMs` and `moveTolerance`. Optional. |

**Returns** Handlers to spread onto the element.

### Types

```ts
export type LongPressOptions = {
  /** How long to hold, in milliseconds. Default `500`. */
  delayMs?: number;
  /** Cancel if the pointer moves more than this many pixels (e.g. the user is scrolling). Default `10`. */
  moveTolerance?: number;
};
/** Spread these onto the element: `<button {...longPress}>`. */
export type LongPressHandlers = {
  onPointerDown: (event: PointerEvent) => void;
  onPointerMove: (event: PointerEvent) => void;
  onPointerUp: () => void;
  onPointerLeave: () => void;
  onPointerCancel: () => void;
  onContextMenu: (event: MouseEvent) => void;
  onClickCapture: (event: MouseEvent) => void;
};
```

## Browser support

Works in all modern browsers.

---

364 B minified and brotlied
Source: https://github.com/vincentri/react-tils/blob/main/src/useLongPress.ts
Docs page: https://vincentri.github.io/react-tils/hooks/useLongPress/
Previous: [useHotkey](https://vincentri.github.io/react-tils/hooks/useHotkey.md)
Next: [useSwipe](https://vincentri.github.io/react-tils/hooks/useSwipe.md)
