-
-
Save ggallon/3ef023424580b70393a43d8269777533 to your computer and use it in GitHub Desktop.
useMousePosition
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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