Skip to content

Instantly share code, notes, and snippets.

@corlaez
Created July 23, 2019 23:17
Show Gist options
  • Save corlaez/1316fcbc3ba3b1c2f954ac56c114e7d5 to your computer and use it in GitHub Desktop.
Save corlaez/1316fcbc3ba3b1c2f954ac56c114e7d5 to your computer and use it in GitHub Desktop.
useMousePosition react hook
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