Created
June 1, 2020 12:30
-
-
Save jackdh/102ff28c3cf64d3758273f3984fd20ec to your computer and use it in GitHub Desktop.
useHover typescript
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 React, { useEffect, useRef, useState } from "react"; | |
type UseHoverType<T extends HTMLElement> = [React.RefObject<T>, boolean]; | |
function useHover<T extends HTMLElement>(): UseHoverType<T> { | |
const [value, setValue] = useState(false); | |
const ref = useRef<T>(null); | |
const handleMouseOver = () => setValue(true); | |
const handleMouseOut = () => setValue(false); | |
useEffect( | |
() => { | |
const node = ref.current; | |
if (node) { | |
node.addEventListener("mouseover", handleMouseOver); | |
node.addEventListener("mouseout", handleMouseOut); | |
return () => { | |
node.removeEventListener("mouseover", handleMouseOver); | |
node.removeEventListener("mouseout", handleMouseOut); | |
}; | |
} | |
}, | |
[ref.current] // Recall only if ref changes | |
); | |
return [ref, value]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
// Usage