Created
November 4, 2020 13:49
-
-
Save takumifukasawa/748dc5cff31fa6002c926bdd1c84f6bc to your computer and use it in GitHub Desktop.
React: mange dom hover custom hooks
This file contains hidden or 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 { useEffect, useRef, useState, RefObject } from "react"; | |
import { useComponentWillUnmount } from "~/hooks/common/useLifecycle"; | |
export default function useHover<T extends HTMLElement>(): [ | |
RefObject<T>, | |
boolean | |
] { | |
let willunmount = false; | |
useComponentWillUnmount(() => { | |
willunmount = true; | |
}); | |
const [isHovered, setIsHovered] = useState<boolean>(false); | |
const ref = useRef<T>(null); | |
const handleMouseEnter = () => { | |
if (!ref.current || willunmount) { | |
return; | |
} | |
setIsHovered(true); | |
}; | |
const handleMouseLeave = () => { | |
if (!ref.current || willunmount) { | |
return; | |
} | |
setIsHovered(false); | |
}; | |
useEffect(() => { | |
ref.current?.addEventListener("mouseenter", handleMouseEnter); | |
ref.current?.addEventListener("mouseleave", handleMouseLeave); | |
return () => { | |
ref.current?.removeEventListener("mouseenter", handleMouseEnter); | |
ref.current?.removeEventListener("mouseleave", handleMouseLeave); | |
}; | |
}, [ref.current]); | |
return [ref, isHovered]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment