useMousePosition
A React hook for tracking mouse position with element-relative coordinates.
Installation
npx shadcn@latest add https://www.shadcn.io/registry/use-mouse-position.json
npx shadcn@latest add https://www.shadcn.io/registry/use-mouse-position.json
pnpm dlx shadcn@latest add https://www.shadcn.io/registry/use-mouse-position.json
bunx shadcn@latest add https://www.shadcn.io/registry/use-mouse-position.json
Usage
import { useMousePosition } from "@/hooks/use-mouse-position"
function MyComponent() {
const [position, ref] = useMousePosition<HTMLDivElement>()
return (
<div ref={ref}>
<p>Mouse position: {position.x}, {position.y}</p>
{position.elementX && (
<p>Relative to element: {position.elementX}, {position.elementY}</p>
)}
</div>
)
}
API
useMousePosition
A hook that tracks the mouse position globally and relative to a referenced element.
Parameters
The hook accepts a generic type parameter for the HTML element type.
Returns
Returns a tuple with:
position
: Position object containing mouse coordinatesref
: React ref to attach to an element for relative positioning
Position Object
type Position = {
x: number // Global mouse X coordinate
y: number // Global mouse Y coordinate
elementX?: number // X coordinate relative to referenced element
elementY?: number // Y coordinate relative to referenced element
elementPositionX?: number // Referenced element's X position
elementPositionY?: number // Referenced element's Y position
}
useMediaQuery
React hook that tracks the state of a media query using the Match Media API for responsive design and user preferences.
useOnClickOutside
Handle clicks outside specified elements with support for multiple refs and event types. Perfect for React applications requiring modal and dropdown behavior with Next.js integration and TypeScript support.