useMouse Position Hook

August 23, 2023

React Hooks

useMouse Position Hook

Thuta Sann

Thuta Sann

custom React hook for Mouse cursor position


Share This Snippet To :

useMousePosition

This custom hook will tell about your current cursor' x and y values.

import { useCallback, useEffect, useState } from 'react' function useMousePosition() { const [mousePosition, setMousePosition] = useState({ x: 0, y: 0 }) const [mouseTrack, setMouseTrack] = useState({ x: 0, y: 0 }) const handleMouseMove = useCallback((e: MouseEvent) => { setMousePosition({ x: e.clientX, y: e.clientY }) if (typeof window !== 'undefined') { setMouseTrack({ x: Number((e.clientX / window.innerWidth).toFixed(2)), y: Number((e.clientY / window.innerHeight).toFixed(2)), }) } }, []) useEffect(() => { document.addEventListener('mousemove', handleMouseMove) return () => document.removeEventListener('mousemove', handleMouseMove) }, [handleMouseMove]) return { mousePosition, mouseTrack, } } export default useMousePosition

Cookie

I baked some cookies that you have to accept, if you want to enjoy my portfolio.
In order to gather information and make improvements, I should use some third-party cookies too, Can I?