use-mouse

Tracks mouse position over the viewport or given element

Import

Usage

Mouse coordinates { x: 0, y: 0 }

import { Text, Code, Group, Box } from '@mantine/core';
import { useMouse } from '@mantine/hooks';

function Demo() {
  const { ref, x, y } = useMouse();

  return (
    <>
      <Group justify="center">
        <Box ref={ref} w={300} h={180} bg="var(--mantine-color-blue-light)" />
      </Group>
      <Text ta="center">
        Mouse coordinates <Code>{`{ x: ${x}, y: ${y} }`}</Code>
      </Text>
    </>
  );
}

If you do not provide ref, mouse position is tracked relative to the document element:

Mouse coordinates { x: 0, y: 0 }

import { Text, Code } from '@mantine/core';
import { useMouse } from '@mantine/hooks';

function Demo() {
  const { x, y } = useMouse();

  return (
    <Text ta="center">
      Mouse coordinates <Code>{`{ x: ${x}, y: ${y} }`}</Code>
    </Text>
  );
}

API

Set resetOnExit option to reset mouse position to 0, 0 when mouse leaves the element:

import { useMouse } from '@mantine/hooks';

const { ref, x, y } = useMouse({ resetOnExit: true });

The hook returns an object with ref and x, y mouse coordinates:

import { useMouse } from '@mantine/hooks';

const {
  ref, // -> pass ref to target element, if not used document element will be used as target element
  x, // -> mouse x position
  y, // -> mouse y position
} = useMouse();

On the first render (as well as during SSR), both x and y values are equal to 0.

Definition

function useMouse<T extends HTMLElement = any>(options?: {
  resetOnExit?: boolean;
}): {
  x: number;
  y: number;
  ref: React.MutableRefObject<T>;
};