Created
September 15, 2020 17:01
-
-
Save eldh/54954e01b40ef6fb812e2c8ee13731dc 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