useMousePressed
React Sensor Hook that tracks mouse pressing state.
Triggered by mousedown touchstart on target element and released by mouseup mouseleave touchend touchcancel on window
useMousePressed returns a tuple of a boolean indicating whether the mouse (or touch) is currently pressed and a source type string ("mouse", "touch", or null). It listens for mousedown/touchstart/dragstart events on the target element and releases on mouseup/mouseleave/touchend/touchcancel/dragend/drop on window. You can configure which input types (touch, drag) to listen for.
When to Use
- Implementing press-and-hold visual feedback (e.g., button ripple effects or scale animations)
- Building drawing or painting tools that need to know when the user is actively pressing
- Detecting whether a drag operation is in progress across the page
Notes
- SSR-safe: Returns
falsefor pressed state andnullfor source type during server-side rendering. No event listeners are attached on the server. - Input sources: By default, mouse, touch, and drag events are all tracked. Disable touch or drag tracking via the
touchanddragoptions. - Related hooks: See also
useMousefor tracking cursor position, anduseLongPressfor detecting extended press gestures.
Usage
Live Editor
function Demo() { const [mouse, type] = useMousePressed(); return ( <div> <p>Pressed: {JSON.stringify(mouse)}</p> <p>SourceType: {JSON.stringify(type)}</p> </div> ); };
Result
API
useMousePressed
Returns
readonly [boolean, UseMousePressedSourceType]: A tuple with the following elements:
- whether the mouse is pressed.
- the pressed source type
Arguments
| Argument | Description | Type | DefaultValue |
|---|---|---|---|
| target | dom element | BasicTarget<Element> | - |
| options | optional params | UseMousePressedOptions | undefined | - |
UseMousePressedOptions
| Property | Description | Type | DefaultValue |
|---|---|---|---|
| touch | Listen to touchstart touchend events | boolean | true |
| drag | Listen to dragstart drop and dragend events | boolean | true |
| initialValue | Initial values | boolean | (() => boolean) | false |
UseMousePressedSourceType
Type
export type UseMousePressedSourceType = 'mouse' | 'touch' | null
BasicTarget
export type BasicTarget<T extends TargetType = Element> = (() => TargetValue<T>) | TargetValue<T> | MutableRefObject<TargetValue<T>>;
TargetValue
type TargetValue<T> = T | undefined | null;
TargetType
type TargetType = HTMLElement | Element | Window | Document | EventTarget;