Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
React Hooks relative mouse position used in
// Inspired by
import {useState,useEffect} from 'react'
export default function useMousePosition(){
let [mousePosition, setMousePosition] = useState([0,0])
function handleMouseMove(e) {
setMousePosition( [e.pageX, e.pageY] );
window.addEventListener("mousemove", handleMouseMove)
return () => {
window.removeEventListener("mousemove", handleMouseMove)
return mousePosition;
import React from 'react'
import useMousePosition from 'useMousePosition'
export function MousePosition(){
let [mouseX,mouseY] = useMousePosition()
return <div>x: {mouseX} y:{mouseY}</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment