Skip to content

Instantly share code, notes, and snippets.

@christianjuth
Last active November 16, 2021 04:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save christianjuth/b651ba571788da7a2fc4987dd78f1625 to your computer and use it in GitHub Desktop.
Save christianjuth/b651ba571788da7a2fc4987dd78f1625 to your computer and use it in GitHub Desktop.
React Hooks
function useMouseSpeed(updateInterval = 500) {
const lastUpdateRef = useRef(Date.now())
const prevPositionRef = useRef<MousePosition | null> (null)
const currentPositionRef = useRef<MousePosition | null> (null)
const [speed, setSpeed] = useState(0)
useEffect(() => {
function trackMouse({ pageX: x, pageY: y }: MouseEvent) {
x = x / window.innerWidth
y = y / window.innerHeight
currentPositionRef.current = { x, y }
}
window.addEventListener('mousemove', trackMouse)
return () => {
window.removeEventListener('mousemove', trackMouse)
}
}, [])
useEffect(() => {
function updateMouseSpeed() {
const prevPosition = prevPositionRef.current
const currentPosition = currentPositionRef.current
if (prevPosition !== null && currentPosition !== null) {
const timeDiffSec = (Date.now() - lastUpdateRef.current) / 1000
const mouseDistance = euclidianDistance(currentPosition, prevPosition)
setSpeed(mouseDistance / timeDiffSec)
}
lastUpdateRef.current = Date.now()
prevPositionRef.current = currentPosition ? { ...currentPosition } : null
}
updateMouseSpeed()
const id = setInterval(updateMouseSpeed, updateInterval)
return () => {
clearInterval(id)
}
}, [updateInterval])
return speed
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment