Skip to content

How to display the cursor position in real-time in design tools

This example demonstrates how to display the cursor position in real-time in design tools using the useMousePosition hook.

Watch the live preview.

tsx
import { useMousePosition } from "./useMousePosition";
import "./styles.css";

export default function App() {
  const { x, y } = useMousePosition();

  return (
    <div className="container">
      <div className="cursor-card">
        x: {x}, y: {y}
      </div>
    </div>
  );
}
typescript
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);
};
css
.container {
  background-color: #f0f0f0;
}

.cursor-card {
  position: fixed;
  top: 10px;
  left: 10px;
  padding: 5px 10px;
  background: #000;
  color: #fff;
  border-radius: 5px;
}