Skip to content

Instantly share code, notes, and snippets.

@eldh
Created September 15, 2020 17:01
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save eldh/54954e01b40ef6fb812e2c8ee13731dc to your computer and use it in GitHub Desktop.
Save eldh/54954e01b40ef6fb812e2c8ee13731dc to your computer and use it in GitHub Desktop.
useMousePosition
import * as React from "react";
import { throttle } from "lodash";
/**
* Mouse position as a tuple of [x, y]
*/
type MousePosition = [number, number];
/**
* Hook to get the current mouse position
*
* @returns Mouse position as a tuple of [x, y]
*/
export const useMousePosition = () => {
const [mousePosition, setMousePosition] = React.useState<MousePosition>([0, 0]);
const updateMousePosition = throttle((ev: MouseEvent) => {
setMousePosition([ev.clientX, ev.clientY]);
}, 200);
React.useEffect(() => {
window.addEventListener("mousemove", updateMousePosition);
return () => window.removeEventListener("mousemove", updateMousePosition);
}, []);
return mousePosition;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment