# useMousePosition > Cursor coordinates within an element. - Category: DOM - Package: `hookli` (install with `npm i hookli`) - Docs: https://hookli.vercel.app/docs/use-mouse-position ## Signature ```ts useMousePosition(ref: RefObject): { x: number | null; y: number | null } ``` ## Parameters - `ref`: `RefObject` — Ref attached to the element the coordinates are measured against. ## Returns - `x`: `number | null` — Cursor X relative to the element's left edge; null until the first mousemove. Updates on every window mousemove, so it can go negative or exceed the element's width. - `y`: `number | null` — Cursor Y relative to the element's top edge; null until the first mousemove. ## Usage ```tsx import { useRef } from "react"; import { useMousePosition } from "hookli"; export function Demo() { const panelRef = useRef(null); const { x, y } = useMousePosition(panelRef); return (
{x === null || y === null ? (

Move your cursor

) : (

{Math.round(x)} × {Math.round(y)}

)}
); } ``` ## Source `src/hooks/useMousePosition.hook.ts` ```ts import { Ref, useEffect, useState } from "react"; interface MousePosition { x: number | null; y: number | null; } export const useMousePosition = ( ref: Ref, ): MousePosition => { const [mousePosition, setMousePosition] = useState({ x: null, y: null, }); useEffect(() => { const updateMousePosition = (event: MouseEvent) => { const { clientX, clientY } = event; if (ref && "current" in ref && ref.current) { const { left, top } = ref.current.getBoundingClientRect(); setMousePosition({ x: clientX - left, y: clientY - top }); } }; window.addEventListener("mousemove", updateMousePosition); return () => { window.removeEventListener("mousemove", updateMousePosition); }; }, [ref]); return mousePosition; }; ```