Skip to content

Instantly share code, notes, and snippets.

@whoisryosuke
Created November 5, 2018 19:22
Show Gist options
  • Star 36 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save whoisryosuke/99f23c9957d90e8cc3eb7689ffa5757c to your computer and use it in GitHub Desktop.
Save whoisryosuke/99f23c9957d90e8cc3eb7689ffa5757c to your computer and use it in GitHub Desktop.
React Hooks - Track user mouse position - via: https://twitter.com/JoshWComeau

Hook

import { useState, useEffect } from "react";

const useMousePosition = () => {
  const [mousePosition, setMousePosition] = useState({ x: null, y: null });

  const updateMousePosition = ev => {
    setMousePosition({ x: ev.clientX, y: ev.clientY });
  };

  useEffect(() => {
    window.addEventListener("mousemove", updateMousePosition);

    return () => window.removeEventListener("mousemove", updateMousePosition);
  }, []);

  return mousePosition;
};

export default useMousePosition;

Usage

function App() {
  const { x, y } = useMousePosition();

  const hasMovedCursor = typeof x === "number" && typeof y === "number";

  return (
    <div className="App">
      <h1>
        {hasMovedCursor
          ? `Your cursor is at ${x}, ${y}.`
          : "Move your mouse around."}
      </h1>
    </div>
  );
}
@nafiudanlawal
Copy link

When you add the {x,y} value from the hook to an onMouseEnter prop, the events is called whenever the mouse moves on the dom instead of only on the component that the event is set for.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment