Docs
Mouse

Mouse

Track and retrieve the position of the mouse cursor

About

The useMouse hook tracks and retrieves the position of the mouse cursor within a component. It provides information such as the current coordinates of the mouse cursor (x and y), the position of the cursor relative to an element within the component (elementX and elementY), and the position of that element on the page (elementPositionX and elementPositionY).

Return Values

NameTypeDescription
stateobjectAn object representing the current mouse position and element information.
refobjectA ref object that can be used to track the mouse position on a specific element.

The state object has the following properties:

NameTypeDescription
state.xnumberThe current horizontal position of the mouse relative to the page.
state.ynumberThe current vertical position of the mouse relative to the page.
state.elementXnumberThe current horizontal position of the mouse relative to the element’s top-left corner.
state.elementYnumberThe current vertical position of the mouse relative to the element’s top-left corner.
state.elementPositionXnumberThe current horizontal position of the element relative to the page.
state.elementPositionYnumberThe current vertical position of the element relative to the page.

Installation

Run the following command:

npx scriptkavi-hooks@latest add mouse

Usage

import { useMouse } from "@/hooks/mouse"
import * as React from "react"
 
import Demo from "./Demo"
 
export default function App() {
  const [mouse, ref] = useMouse()
 
  const xIntersecting = mouse.elementX > 0 && mouse.elementX < 300
  const yIntersecting = mouse.elementY > 0 && mouse.elementY < 300
  const isIntersecting = xIntersecting && yIntersecting
 
  return (
    <section>
      <h1>useMouse</h1>
      <article
        ref={ref}
        style={{ width: "300px", height: "300px" }}
        className={isIntersecting ? "active" : ""}
      >
        Use a ref to add coords relative to the element
      </article>
      <Demo {...mouse} />
    </section>
  )
}