Created
July 23, 2019 23:17
-
-
Save corlaez/1316fcbc3ba3b1c2f954ac56c114e7d5 to your computer and use it in GitHub Desktop.
useMousePosition react hook
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 { useState, useEffect } from 'react' | |
export const useMousePosition = () => { | |
const [position, setPosition] = useState({ x: 0, y: 0 }); | |
useEffect(() => { | |
const setFromEvent = (e: any) => setPosition({ | |
x: e.clientX, | |
y: e.clientY | |
}); | |
window.addEventListener("mousemove", setFromEvent); | |
return () => { | |
window.removeEventListener("mousemove", setFromEvent); | |
}; | |
}, []); | |
return position; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment