Skip to content

useMousePosition

React hook to track the current position of the mouse on the screen.

Add the hook via the CLI:

sh
npx @novajslabs/cli add useMousePosition
sh
npx @novajslabs/cli add useMousePosition
sh
pnpm dlx @novajslabs/cli add useMousePosition

Or copy and paste the code into your project:

ts
import { useSyncExternalStore } from "react";

interface MousePosition {
  x: number;
  y: number;
}

let mousePosition: MousePosition = { x: 0, y: 0 };

export const useMousePosition = (): MousePosition => {
  const subscribe = (callback: () => void) => {
    const handleMouseMove = (event: MouseEvent) => {
      mousePosition = {
        x: event.clientX,
        y: event.clientY,
      };
      callback();
    };

    window.addEventListener("mousemove", handleMouseMove);
    return () => {
      window.removeEventListener("mousemove", handleMouseMove);
    };
  };

  const getSnapshot = (): MousePosition => mousePosition;

  const getServerSnapshot = (): MousePosition => ({ x: 0, y: 0 });

  return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
};
js
import { useSyncExternalStore } from "react";

let mousePosition = { x: 0, y: 0 };

export const useMousePosition = () => {
  const subscribe = (callback) => {
    const handleMouseMove = (event) => {
      mousePosition = {
        x: event.clientX,
        y: event.clientY,
      };
      callback();
    };

    window.addEventListener("mousemove", handleMouseMove);
    return () => {
      window.removeEventListener("mousemove", handleMouseMove);
    };
  };

  const getSnapshot = () => mousePosition;

  const getServerSnapshot = () => ({ x: 0, y: 0 });

  return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
};

Requirements

React 18.0 or higher

Return values

x

Type: number

The horizontal position of the mouse in pixels relative to the viewport.

y

Type: number

The vertical position of the mouse in pixels relative to the viewport.

Examples of common use cases