Skip to content

Instantly share code, notes, and snippets.

@takumifukasawa
Created November 4, 2020 13:49
Show Gist options
  • Save takumifukasawa/748dc5cff31fa6002c926bdd1c84f6bc to your computer and use it in GitHub Desktop.
Save takumifukasawa/748dc5cff31fa6002c926bdd1c84f6bc to your computer and use it in GitHub Desktop.
React: mange dom hover custom hooks
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