Last active
October 4, 2021 11:21
-
-
Save gragland/cfc4089e2f5d98dde5033adc44da53f8 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); | |
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]; | |
} |
I don't really think you need the useRef hook.
you could just use the useState hook and the onMouseEnter and onMouseLeave as props on the component.
what do you think?
import React,{useState,useRef,useEffect} from "react"
export default function Image({className,image}){
const [ishover, setIsHover] = useState(false)
console.log(ishover)
return(
<div
className={`${className} image-container`}
onMouseEnter={() => setIsHover(true)}
onMouseLeave={() => setIsHover(false)}
>
<img src={image.url} className="image-grid"/>
</div>
)
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I had an issue with the last event being fired being a
mouseover
event. I switched themouseover
tomouseenter
andmouseout
tomouseleave
which solved it. Any drawbacks to this method? It also limits the amount of events firing as it doesn't fire on child elements.