Last active
August 27, 2024 14:33
-
-
Save rlueder/1c58dd41e19f562416ca453ec87a3220 to your computer and use it in GitHub Desktop.
A React hook that exposes the user's mouse position
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 { useCallback, useRef, useState } from "react"; | |
| const useMousePosition = () => { | |
| const [mousePosition, setMousePosition] = useState({ | |
| left: 0, | |
| top: 0, | |
| }); | |
| const handleMouseMove = useCallback( | |
| (e) => | |
| setMousePosition({ | |
| left: e.pageX, | |
| top: e.pageY, | |
| }), | |
| [] | |
| ); | |
| const ref = useRef(); | |
| const callbackRef = useCallback( | |
| (node) => { | |
| if (ref.current) { | |
| ref.current.removeEventListener("mousemove", handleMouseMove); | |
| } | |
| ref.current = node; | |
| if (ref.current) { | |
| ref.current.addEventListener("mousemove", handleMouseMove); | |
| } | |
| }, | |
| [handleMouseMove] | |
| ); | |
| return [callbackRef, mousePosition]; | |
| }; | |
| export default useMousePosition; | |
| // An example below on how to use it: | |
| // const App = () => { | |
| // const [ref, mousePosition] = useMousePosition(); | |
| // useEffect(() => { | |
| // // do something with the mouse position values here | |
| // console.log(mousePosition); | |
| // }, [mousePosition]); | |
| // return (<div className="App" ref={ref} />); | |
| // }; | |
| // export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment