Skip to content

Instantly share code, notes, and snippets.

@ValentaTomas
Created February 23, 2023 21:29
Show Gist options
  • Save ValentaTomas/b0d198f9d4551a418511b56d6765e668 to your computer and use it in GitHub Desktop.
Save ValentaTomas/b0d198f9d4551a418511b56d6765e668 to your computer and use it in GitHub Desktop.
Helper hook for creating divs attached to mouse cursor
import { useEffect, useState } from 'react'
export type UpdateIndicator = (x: number, y: number) => void
export function useMouseIndicator(indicatorFactory?: () => { el: HTMLElement; update: UpdateIndicator; }) {
const [isActive, setIsActive] = useState(false)
useEffect(function attach() {
if (!isActive) return
if (!indicatorFactory) return
const { el, update } = indicatorFactory()
const handleWindowMouseMove = (event: MouseEvent) => {
const x = event.clientX
const y = event.clientY
update(x, y)
}
window.addEventListener('mousemove', handleWindowMouseMove)
document.body.appendChild(el)
return () => {
window.removeEventListener('mousemove', handleWindowMouseMove)
document.body.removeChild(el)
}
}, [
isActive,
indicatorFactory,
])
return setIsActive
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment