Skip to content

Instantly share code, notes, and snippets.

@evolify
Created July 26, 2022 06:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save evolify/d6ffaae840f0755f72a4e6aea8502a7d to your computer and use it in GitHub Desktop.
Save evolify/d6ffaae840f0755f72a4e6aea8502a7d to your computer and use it in GitHub Desktop.
useMousePosition
import { useState, useEffect } from "react";
export default function useMousePosition() {
const [mousePosition, setMousePosition] = useState({ x: null, y: null });
useEffect(() => {
const updateMousePosition = (ev) => {
setMousePosition({ x: ev.clientX, y: ev.clientY });
};
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