h3/use's logo

h3/use

Command Palette

Search for a command to run...

useMouse

Tracks the mouse position in the element and document.

useMouse
This component uses the useMouse hook to track the mouse position.

Mouse position in document - x:0 y:0

Mouse position in element - x:0 y:0

Element position- x:0 y:0

Element dimensions - 0x0

Try moving your mouse around the screen.

Installation

Props

PropTypeDefaultDescription
refRefObject<HTMLElement>nullThe ref of the element to track the mouse position
trackOutside?booleanfalseUpdate state even outside the element
clampToZero?booleanfalseClamps elX/elY to >= 0

Data

PropTypeDescription
docXnumberThe X position of the mouse in the document
docYnumberThe Y position of the mouse in the document
posXnumberThe X position of the mouse in the element
posYnumberThe Y position of the mouse in the element
elXnumberThe X position of the mouse in the element
elYnumberThe Y position of the mouse in the element
elHnumberThe height of the element
elWnumberThe width of the element

Key Features & Details

Required Ref & Error Handling

  • The ref prop is required and must point to an HTMLElement.
  • In development, an error is logged if ref is missing or invalid.

State Updates & Event Handling

  • The hook listens to the mousemove event on the document.
  • State is only updated if any value changes, for performance.
  • If trackOutside is false, state only updates when the mouse is inside the element; if true, updates everywhere.
  • If clampToZero is true, elX and elY are clamped to zero or greater.

Returned Data

  • The hook returns an object with mouse position in the document, relative to the element, and element dimensions.

Cleanup

  • The event listener is removed automatically when the component unmounts.

Caveats & Best Practices

  • The hook is intended for use in the browser; on the server, it will always return zeros.
  • Ensure the ref is stable and points to a visible element.
  • If the element is not in the DOM, all values will be zero.
  • For best performance, avoid unnecessary re-renders by memoizing the ref.

Examples

Basic Usage

const ref = useRef<HTMLDivElement>(null);
const mouse = useMouse({ ref });
return (
  <div ref={ref}>
    elX: {mouse.elX}, elY: {mouse.elY}
  </div>
);

Track Mouse Outside Element

const ref = useRef<HTMLDivElement>(null);
const mouse = useMouse({ ref, trackOutside: true });

Clamp Mouse Position to Zero

const ref = useRef<HTMLDivElement>(null);
const mouse = useMouse({ ref, clampToZero: true });