useMousePosition
A React hook that tracks the mouse cursor's coordinates with high precision.
Overview
useMousePosition allows you to build deeply interactive UIs that react to the user's focus. Whether it's a soft spotlight aura, a 3D perspective shift, or complex canvas logic, this hook provides a clean, performant way to access viewport coordinates.
Demo
API Reference
function useMousePosition(): {
x: number | null,
y: number | null
}Returns
| Name | Type | Description |
|---|---|---|
x | number | null | Horizontal coordinate relative to the viewport. null if the mouse hasn't moved yet. |
y | number | null | Vertical coordinate relative to the viewport. null if the mouse hasn't moved yet. |
Usage Examples
Simple Cursor Tracking
import { useMousePosition } from 'react-hooks-ts'
function MouseInfo() {
const { x, y } = useMousePosition()
return (
<div>
Cursor is at: ({x}, {y})
</div>
)
}Features
- ⚡ Performant - Uses a single optimized event listener.
- 🧹 Self-Cleaning - Automatically removes listeners on unmount.
- 🎯 High Precision - Direct access to browser
clientXandclientY. - 🧩 SSR Safe - Handles window detection gracefully for Next.js environments.