Skip to content

Instantly share code, notes, and snippets.

@chrisdrackett
Forked from eldh/useMousePosition.ts
Created September 17, 2020 19:33
Show Gist options
  • Save chrisdrackett/6edddf48541ce1ccd2599fa96423c7cf to your computer and use it in GitHub Desktop.
Save chrisdrackett/6edddf48541ce1ccd2599fa96423c7cf 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