Install

npm
npm i use-any-hook

Description

The useMousePosition hook allows you to track the mouse position within a specific DOM element. This is useful for creating interactive components that need to respond to the user’s mouse movements, such as custom tooltips, draggable elements, or dynamic visual effects.

Parameters

NameTypeDescription
refReact.RefObjectA ref to the DOM element within which the mouse position should be tracked.

Return Values:

NameTypeDescription
xnumberThe current x-coordinate of the mouse position within the specified element.
ynumberThe current y-coordinate of the mouse position within the specified element.

Example

useMousePosition.example.tsx
import { useMousePosition } from "use-any-hook";

function MyComponent() {
  const ref = React.useRef(null);
  const { x, y } = useMousePosition(ref);

  return (
    <div ref={ref}>
      Mouse Position: `x-axis: ${x}, y-axis: ${y}`
    </div>
  );
}