Created
February 19, 2019 17:35
-
-
Save DroopyTersen/0970aa54fa6400d9d0bbe7f5e017492d to your computer and use it in GitHub Desktop.
Composing Behavior with React hooks - useHover
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 { useState, useRef, useEffect } from "react"; | |
export default function useHover() { | |
const [isHovered, setIsHovered] = useState(false); | |
const hoverRef = useRef(null); | |
const handleMouseOver = () => setIsHovered(true); | |
const handleMouseOut = () => setIsHovered(false); | |
useEffect( | |
() => { | |
const elem = hoverRef.current; | |
if (elem) { | |
elem.addEventListener("mouseover", handleMouseOver); | |
elem.addEventListener("mouseout", handleMouseOut); | |
return () => { | |
elem.removeEventListener("mouseover", handleMouseOver); | |
elem.removeEventListener("mouseout", handleMouseOut); | |
}; | |
} | |
}, | |
[hoverRef.current] | |
); // Recall only if ref changes | |
return [hoverRef, isHovered]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment