useMouse

A React Hook that tracks mouse position.

Demo

Try to scroll the page or move your mouse around to see the difference between various types.

Source
Type: page (default):
(0, 0, null)
Type: client:
(0, 0, null)
Type: screen:
(0, 0, null)
Type: movement (useful when pointer locked):
(0, 0)
isActive:
true

Usage

See API for more details.

Source

Click links below to view source on GitHub.

API

const { x, y, position, sourceType, stop } = useMouse(options)

Options

export type UseMouseOptions = { /** * Type of coordinates to extract from the event. * * @defaultValue 'page' */ type?: UseMouseCoordType | UseMouseEventExtractor /** * Target element to attach the event listeners. * * @defaultValue window */ target?: Window | EventTarget | null | undefined /** * Whether to enable touch events. * * @defaultValue true */ touch?: boolean /** * Whether to enable scroll events. * * @defaultValue true */ scroll?: boolean /** * Whether to reset the position when touch ends. * * @defaultValue false */ resetOnTouchEnds?: boolean /** * Initial position. * * @defaultValue { x: 0, y: 0 } */ initialValue?: Position /** * Whether to start to update position immediately. * * @defaultValue false */ immediate?: boolean }

Returns

Retuerns contain Pausable instance that can be paused, resumed.

See Pausable for more details.

export type Position = { /** * X coordinate */ x: number /** * Y coordinate */ y: number } export type UseMouseReturns = Position & Pausable & { /** * mouse event position. */ position: Position /** * Source type of the event. */ sourceType: UseMouseSourceType /** * stop the mouse event listener immediately. */ stop(): void }