Installation
Props
| Prop | Type | Default | Description |
|---|---|---|---|
ref | RefObject<HTMLElement> | null | The ref of the element to track the mouse position |
trackOutside? | boolean | false | Update state even outside the element |
clampToZero? | boolean | false | Clamps elX/elY to >= 0 |
Data
| Prop | Type | Description |
|---|---|---|
docX | number | The X position of the mouse in the document |
docY | number | The Y position of the mouse in the document |
posX | number | The X position of the mouse in the element |
posY | number | The Y position of the mouse in the element |
elX | number | The X position of the mouse in the element |
elY | number | The Y position of the mouse in the element |
elH | number | The height of the element |
elW | number | The width of the element |
Key Features & Details
Required Ref & Error Handling
- The
refprop is required and must point to anHTMLElement. - In development, an error is logged if
refis missing or invalid.
State Updates & Event Handling
- The hook listens to the
mousemoveevent on the document. - State is only updated if any value changes, for performance.
- If
trackOutsideisfalse, state only updates when the mouse is inside the element; iftrue, updates everywhere. - If
clampToZeroistrue,elXandelYare 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
refis 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 });