Join our Discord Community

React useMousePosition Hook

React useMousePosition hook for mouse tracking. Get real-time cursor coordinates with element-relative positioning and TypeScript support for Next.js apps.

Need help with mouse tracking performance?

Join our Discord community for help from other developers.


Ever tried to track mouse position in React and ended up with addEventListener chaos, performance issues from constant mousemove events, or coordinate calculation headaches? You know the drill—manually managing event listeners, calculating relative positions, dealing with scroll offsets and transforms. This free open source React useMousePosition custom hook handles all that mouse tracking complexity so you can focus on building interactive features instead of debugging coordinate math in your React applications.

useMousePosition showcase

Real-time mouse tracking with global and element-relative coordinates:

Loading component...

This free open source React hook simplifies cursor position tracking with TypeScript support for modern JavaScript applications. Whether you're building tooltips, drag-and-drop interfaces, or custom cursors in your Next.js projects, this React hook keeps your mouse coordinates accurate and performant.

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

Why most mouse tracking implementations suck

Look, you could keep adding mousemove listeners and calculating coordinates manually. But then you hit the mouse tracking complexity—performance bottlenecks from frequent events, coordinate system confusion, memory leaks from forgotten removeEventListener calls in React applications.

Most developers add raw mousemove listeners without proper cleanup, causing memory leaks when components unmount in TypeScript components. Or they calculate element-relative positions manually and get confused by scroll offsets, transforms, and coordinate systems. Some throttle events incorrectly, leading to choppy cursor tracking that breaks user interactions in Next.js projects.

This React hook uses optimized event handling under the hood, with automatic cleanup and efficient position calculations in JavaScript applications. The browser handles all the coordinate transformations, plus you get both global and element-relative positioning in one call.

Plus it handles all the edge cases—element bounds checking, scroll compensation, transform matrix calculations in React development. No more scattered event listeners or performance issues from unthrottled mousemove events.

This free open source React hook manages mouse state while you focus on building features. Whether you're creating React applications, Next.js interfaces, or TypeScript components, reliable position tracking keeps your JavaScript development smooth.

Features

  • Real-time tracking with optimized mousemove event handling and automatic cleanup in React applications
  • Dual coordinate systems providing both global viewport and element-relative positioning in TypeScript components
  • Performance optimized with efficient event delegation and minimal re-renders in Next.js projects
  • Type safety with full TypeScript support and generic element types for JavaScript development
  • Element integration using React refs for seamless component attachment in React frameworks
  • Memory safe with automatic event listener cleanup on unmount in modern applications
  • Free open source designed for modern React development workflows

When you'll actually use this

Real talk—this isn't for basic hover effects in React applications. CSS :hover handles most cursor interactions perfectly. But when you need precise cursor coordinates for interactive logic or custom positioning, this React hook delivers in Next.js projects.

Perfect for:

  • Custom tooltips - Position tooltips precisely relative to cursor location built with TypeScript
  • Drag and drop - Track drag operations with smooth coordinate updates using React patterns
  • Interactive graphics - Canvas drawing or SVG manipulation based on cursor position in JavaScript applications
  • Custom cursors - Create follow-cursor effects or cursor-based animations in React components
  • Proximity effects - Trigger animations based on cursor distance from elements in Next.js applications
  • Crosshair overlays - Build design tools with cursor-based measurement or selection using TypeScript safety

API Reference

useMousePosition

useMousePosition<T extends HTMLElement = HTMLElement>(): [Position, RefObject<T>]
ParameterTypeDescription
THTMLElementGeneric type parameter for the target HTML element

Return Value

Returns a tuple: [position, ref]

PropertyTypeDescription
positionPositionCurrent mouse position object with coordinates
refRefObject<T>React ref to attach to target element for relative positioning

Position Object

type Position = {
  x: number; // Global mouse X coordinate relative to viewport
  y: number; // Global mouse Y coordinate relative to viewport
  elementX?: number; // X coordinate relative to referenced element
  elementY?: number; // Y coordinate relative to referenced element
  elementPositionX?: number; // Referenced element's X position in viewport
  elementPositionY?: number; // Referenced element's Y position in viewport
};

Common gotchas

Mouse events fire frequently: The React hook is optimized but mousemove events can still impact performance in complex applications. Consider debouncing or throttling if you're doing expensive calculations with position data in React applications.

Element coordinates depend on ref attachment: The elementX and elementY values are only available when the ref is properly attached to a DOM element in TypeScript components. Always check for their existence before using relative positioning.

Scroll and transform effects apply: The React hook calculates positions relative to the current viewport and element position in Next.js projects. Scrolling or CSS transforms on parent elements will affect the coordinate calculations.

Event cleanup happens automatically: The hook manages event listeners internally and cleans them up on unmount in JavaScript applications, but be mindful of creating too many concurrent mouse tracking instances.

Performance impact with many instances: Multiple useMousePosition hooks can create performance issues in React frameworks. Consider using a global mouse position provider for applications with many tracking needs.

Touch devices limitations: Mouse tracking doesn't work on touch devices where there's no persistent cursor position in TypeScript projects. Consider alternative interaction patterns for mobile users.

Questions you might have