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

Precision Aura

High-fidelity cursor tracking with reactive depth.

Live Coordinates
X
Y
Tracking ModeViewport Relative

API Reference

function useMousePosition(): {
  x: number | null,
  y: number | null
}

Returns

NameTypeDescription
xnumber | nullHorizontal coordinate relative to the viewport. null if the mouse hasn't moved yet.
ynumber | nullVertical 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 clientX and clientY.
  • 🧩 SSR Safe - Handles window detection gracefully for Next.js environments.