-
-
Save mbelsky/909c7a6b9bde3289e91a6448ae1a74b3 to your computer and use it in GitHub Desktop.
React Hook recipe from https://usehooks.com. Demo: https://codesandbox.io/s/01w2zmj010
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 { useRef, useState, useEffect } from 'react'; | |
// Usage | |
function App() { | |
const [hoverRef, isHovered] = useHover(); | |
return ( | |
<div ref={hoverRef}> | |
{isHovered ? '😁' : '☹️'} | |
</div> | |
); | |
} | |
// Hook | |
function useHover() { | |
const [value, setValue] = useState(false); | |
const ref = useRef(null); | |
useEffect( | |
() => { | |
const node = ref.current; | |
if (node) { | |
const handleMouseOver = () => setValue(true); | |
const handleMouseOut = () => setValue(false); | |
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