HooksuseMousePosition

useMousePosition()

The useMousePosition() hook tracks the cursor‘s current position on the global window object. It returns the X and Y coordinates, updating them in real-time as the user moves their mouse.

Import

typescript
import { useMousePosition } from 'the-react-hooks';

Usage

Move your cursor anywhere on the screen.

Position X
0
Position Y
0
Component.tsx
import { useMousePosition } from 'the-react-hooks';

export const Component = () => {
  const { x, y } = useMousePosition();

  return (
    <div>
      <p>
        Mouse Coordinates: {x}, {y}
      </p>
    </div>
  );
}

API

Arguments

This hook does not accept any arguments.

Returns

Returns an object containing the coordinates:
  • x number The horizontal coordinate (relative to the document).
  • y number The vertical coordinate (relative to the document).