-
-
Save Guria/9e020d5025dd4e5f1d3f6bcff87a947c to your computer and use it in GitHub Desktop.
React Hook recipe from https://usehooks.com
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 { useRef, useState, useEffect } from 'react'; | |
// Usage | |
function App() { | |
const [ref, isHovered] = useHover(ref); | |
return ( | |
<div ref={ref}> | |
{isHovered ? '😁' : '☹️'} | |
</div> | |
); | |
} | |
// Hook | |
function useHover() { | |
const [value, setValue] = useState(false); | |
const handleMouseOver = () => setValue(true); | |
const handleMouseOut = () => setValue(false); | |
const ref = useRef(null); | |
useEffect(() => { | |
if (ref && ref.current) { | |
ref.current.addEventListener('mouseover', handleMouseOver); | |
ref.current.addEventListener('mouseout', handleMouseOut); | |
} | |
return () => { | |
if (ref && ref.current) { | |
ref.current.removeEventListener('mouseover', handleMouseOver); | |
ref.current.removeEventListener('mouseout', handleMouseOut); | |
} | |
}; | |
}, []); | |
return [ref, value]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment