Skip to Content
ohooks

useMouse

Tracks mouse cursor coordinates across the document, viewport, screen, and an optional target element using requestAnimationFrame.

Loading preview...

The useMouse hook listens to mousemove and dragover events (throttled via requestAnimationFrame) and reports cursor coordinates relative to the document (x, y), viewport (clientX, clientY), screen (screenX, screenY), and an optional target element (elementX, elementY).

Installation

pnpm dlx shadcn@latest add https://ohooks.vercel.app/r/useMouse.json

Usage

Examples

Spotlight Effect Relative to an Element

Pass a target element ref to compute elementX and elementY relative to that element's top-left corner.

Global Viewport Cursor Tracking

Call useMouse() without arguments to track global document and viewport coordinates.

API Reference

MousePositionState

Cursor and element coordinate values returned by the hook.

Property
Specification
x
number
Horizontal coordinate relative to the whole document (pageX)
y
number
Vertical coordinate relative to the whole document (pageY)
clientX
number
Horizontal coordinate relative to the viewport (clientX)
clientY
number
Vertical coordinate relative to the viewport (clientY)
screenX
number
Horizontal coordinate relative to the user's screen (screenX)
screenY
number
Vertical coordinate relative to the user's screen (screenY)
elementX
number
Horizontal coordinate relative to the target element
elementY
number
Vertical coordinate relative to the target element
elementPositionX
number
Target element's horizontal document offset
elementPositionY
number
Target element's vertical document offset