Skip to content

useLongPress

Hook to execute a callback on a long press event.

Demo

INFO

The component has:

  • a pressCounter state variable.
  • a clickCounter state variable.
  • a RefCallback cbRef attached to a button Press me. It is returned from useLongPress hook that has a cb a function to update pressCounter state and normalPress option to update clickCounter state.
  • it renders a div with Press me button and two p elements that display pressCounter and clickCounter.

When the button is clicked for less than a second, normalPress callback is executed, otherwise long press callback is executed.

Loading demo…
Show source code
tsx
import { useState } from "react";
import { useLongPress } from "../../../..";

export const UseLongPress = () => {
	const [pressCounter, setPressCounter] = useState(0);
	const [clickCounter, setClickCounter] = useState(0);
	const [color, setColor] = useState(-1)


	const cbRef = useLongPress<HTMLButtonElement>(() => {
		setPressCounter((s) => s + 1);
		setColor(1);
	}, {
		normalPress: () => setClickCounter((s) => s + 1),
		onStart() {
			setColor(0);
		},
		onFinish() {
			setColor(-1);
		},
	});

	return (
		<div>
			<button ref={cbRef} type="button" style={{ ...(color === -1 ? {} : { backgroundColor: color === -1 ? "inherit" : color === 0 ? "#8e830f" : "#0b5f07"})}}>
				Press me
			</button>
			<p>pressCounter: {pressCounter}</p>
			<p>clickCounter: {clickCounter}</p>
		</div>
	);
}

Types

useLongPressCallback

  • @template E - The event type received by the callback.

Callback type used by useLongPress.

ts
export type useLongPressCallback<E extends Event = Event> = (evt: E) => void;

useLongPressOptions

  • @template E - The event type received by the callbacks.

Options accepted by useLongPress.

PropertyTypeRequiredDescription
durationnumberDuration in milliseconds the pointer must be held before the long-press callback fires. Defaults to 1000 ms when omitted.
normalPress(evt: E) => voidCalled when the pointer is released before duration has elapsed (a "normal" short press). Use this to handle both tap and long-press on the same element.
onStart(evt: E) => voidCalled when the pointer is pressed down on the target element, before the long-press duration has elapsed.
onFinish(evt: E) => voidCalled when the press ends, regardless of whether the long-press threshold was reached (i.e. on pointerup or pointerleave).

UseLongPressResult

  • @template T - The element type the ref callback is attached to.

Return value of useLongPress.

A React ref callback to attach to the target element. Wiring this ref is required for the hook to register its pointer event listeners and detect long-press gestures.

ts
export type UseLongPressResult<T extends Element = Element> = RefCallback<T>;

Released under the MIT License.