useMouse

Track and retrieve the position of the mouse cursor with useMouse.

Install:

npm i @uidotdev/usehooks

Description:

The useMouse hook is useful for tracking and retrieving the position of the mouse cursor within a component. By utilizing this hook, developers can easily access information such as the current coordinates of the mouse cursor (x and y), the position of the mouse cursor relative to an element within the component (elementX and elementY), and the position of that element on the page (elementPositionX and elementPositionY).

Parameters

None.

Return Value

The useMouse hook returns an array with two elements:

NameTypeDescription
stateobjectAn object representing the current mouse position and element information.
refobjectA ref object that can be used to track the mouse position on a specific element.

The state object has the following properties:

NameTypeDescription
state.xnumberThe current horizontal position of the mouse relative to the page.
state.ynumberThe current vertical position of the mouse relative to the page.
state.elementXnumberThe current horizontal position of the mouse relative to the element’s top-left corner.
state.elementYnumberThe current vertical position of the mouse relative to the element’s top-left corner.
state.elementPositionXnumberThe current horizontal position of the element relative to the page.
state.elementPositionYnumberThe current vertical position of the element relative to the page.

Demo:

Example:

More Hooks:

Sort: