Skip to content

Instantly share code, notes, and snippets.

@jakewtaylor
Created November 13, 2018 14:10
Show Gist options
  • Save jakewtaylor/c07573ec5f6a9ea66cb704b8e46eebd3 to your computer and use it in GitHub Desktop.
Save jakewtaylor/c07573ec5f6a9ea66cb704b8e46eebd3 to your computer and use it in GitHub Desktop.
useMouseCoordinates()
const Tooltip = (props) => {
const [x, y] = useMouseCoordinates();
return (
<p>Mouse is at x: {x}, y: {y}.</p>
);
}
import { useState, useEffect } from 'react';
export const useMouseCoordinates = () => {
const [x, setX] = useState(0);
const [y, setY] = useState(0);
const handleMouseMove = (e) => {
setX(e.pageX);
setY(e.pageY);
};
useEffect(() => {
window.addEventListener('mousemove', handleMouseMove);
return () => window.removeEventListener('mousemove', handleMouseMove);
});
return [x, y];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment