Skip to content

Instantly share code, notes, and snippets.

@rlueder
Last active August 27, 2024 14:33
Show Gist options
  • Select an option

  • Save rlueder/1c58dd41e19f562416ca453ec87a3220 to your computer and use it in GitHub Desktop.

Select an option

Save rlueder/1c58dd41e19f562416ca453ec87a3220 to your computer and use it in GitHub Desktop.
A React hook that exposes the user's mouse position
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