useMouse
function useMouse(ref?: RefObject<Element | null>): MouseState | null;
interface MouseState {
readonly clientX: number;
readonly clientY: number;
readonly pageX: number;
readonly pageY: number;
readonly screenX: number;
readonly screenY: number;
readonly element: MouseElementPosition | null;
}
interface MouseElementPosition {
readonly x: number;
readonly y: number;
readonly width: number;
readonly height: number;
}
Tracks the mouse: where it is in the viewport, the page (including scrolling) and the screen,
in CSS pixels. It re-renders as the mouse moves, at most once per animation frame. Given a
ref, element also holds the position within that element, which is negative or beyond its
size outside it, and the element's size, measured on each update. It is null on the server
and until the mouse first moves over the page, and stops listening on unmount.
Live demo
Spotlight off
Move your mouse over the card.
Example
import { useRef } from "react";
import { useMouse } from "react-honey-hooks";
function Spotlight() {
const card = useRef<HTMLDivElement>(null);
const mouse = useMouse(card);
return (
<div
ref={card}
style={{
background: mouse?.element
? `radial-gradient(circle at ${String(mouse.element.x)}px ${String(mouse.element.y)}px, #fff3, transparent 40%)`
: undefined,
}}
/>
);
}