Skip to content

useDoubleClick

Hook to handle double click event. Double clicking in react as well as with vanilla js, it is possible to manage it but it is not possible to have both managers on the same element. Thanks to this hook it is possible to do this, and it works with all events that can be associated with a user click (for example mousedown but also touchstart).

Demo

INFO

The component renders a tag p with message state variable and a button which has an onClick handler. Its handler is handler, the returned function of useDoubleClick hook that set message value in different way by click type.

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

export const UseDoubleClick = () => {
	const [message, setMessage] = useState("");
	const handler = useDoubleClick({
		doubleClick: useCallback(() => {
			setMessage("Double click executed.")
		}, []),
		singleClick: useCallback(() => {
			setMessage("Single click executed.")
		}, [])
	});

	return <div>
		<p>Message: {message}</p>
		<button onClick={handler}>Click/DoubleClick</button>
	</div>
}

Types

UseDoubleClickProps

  • @template T - The element type the synthetic event originates from.
  • @template E - The underlying native event type.

Parameters accepted by useDoubleClick.

ts
export type UseDoubleClickProps<T extends Element = Element, E extends Event = Event> =
| ((evt: SyntheticEvent<T, E>) => Promise<void> | void)
| {
	/**
	* Handler invoked when a double-click gesture is detected within the
	* configured `tolerance` window.
	*/
	doubleClick: (evt: SyntheticEvent<T, E>) => Promise<void> | void;

	/**
	* Optional handler invoked when a single click is detected and no second
	* click follows within the `tolerance` window. When omitted, single clicks
	* are ignored.
	*/
	singleClick?: (evt: SyntheticEvent<T, E>) => Promise<void> | void;

	/**
	* Maximum number of milliseconds allowed between two clicks for them to be
	* considered a double-click. Defaults to `300` ms when omitted.
	*/
	tolerance?: number;
};

UseDoubleClickResult

  • @template T - The element type the synthetic event originates from.
  • @template E - The underlying native event type.

Return value of useDoubleClick.

A stable event handler to attach to a React element's onClick (or equivalent) prop. Internally debounces clicks and dispatches to either singleClick or doubleClick based on the configured tolerance.

ts
export type UseDoubleClickResult<T extends Element = Element, E extends Event = Event> = (evt: SyntheticEvent<T, E>) => Promise<void> | void;

Released under the MIT License.