Created
August 11, 2021 16:07
-
-
Save dhinesh03/a32ab043634ff15c33d17de890563e93 to your computer and use it in GitHub Desktop.
React Hook - sample code to capture mouse coordinates
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState, useCallback, useEffect, useRef } from 'react'; | |
function useEventListener(eventName, handler, element = window) { | |
// Create a ref that stores handler | |
const savedHandler = useRef(); | |
// Update ref.current value if handler changes. | |
// This allows our effect below to always get latest handler ... | |
// ... without us needing to pass it in effect deps array ... | |
// ... and potentially cause effect to re-run every render. | |
useEffect(() => { | |
savedHandler.current = handler; | |
}, [handler]); | |
useEffect(() => { | |
// Make sure element supports addEventListener | |
const isSupported = element && element.addEventListener; | |
if (!isSupported) return; | |
// Create event listener that calls handler function stored in ref | |
const eventListener = event => savedHandler.current(event); | |
// Add event listener | |
element.addEventListener(eventName, eventListener); | |
// Remove event listener on cleanup | |
return () => { | |
element.removeEventListener(eventName, eventListener); | |
}; | |
}, | |
[eventName, element] // Re-run if eventName or element changes | |
); | |
} | |
export default function App() { | |
// State for storing mouse coordinates | |
const [coords, setCoords] = useState({ x: 0, y: 0 }); | |
// Event handler utilizing useCallback ... | |
// ... so that reference never changes. | |
const handler = useCallback( | |
({ clientX, clientY }) => { | |
// Update coordinates | |
setCoords({ x: clientX, y: clientY }); | |
}, | |
[setCoords] | |
); | |
// Add event listener using our hook | |
useEventListener('mousemove', handler); | |
return ( | |
<h1> | |
The mouse position is ({coords.x}, {coords.y}) | |
</h1> | |
); | |
} |
@isaac-gilmour-asknicely Yes It is a fair comparison, As you mentioned, simply adding onMouseMove will work but it will end up a performance issue due to frequent garbage collections. we might not want to constantly be registering and un registering listeners every single render right?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
not really a fair comparison: https://stackoverflow.com/questions/58028788/how-to-add-a-mousemove-event-listener-to-a-component-cursor-which-is-moved-wit