Skip to content

Instantly share code, notes, and snippets.

@gragland
Last active October 4, 2021 11:21
Show Gist options
  • Save gragland/cfc4089e2f5d98dde5033adc44da53f8 to your computer and use it in GitHub Desktop.
Save gragland/cfc4089e2f5d98dde5033adc44da53f8 to your computer and use it in GitHub Desktop.
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];
}
@GlynL
Copy link

GlynL commented Dec 4, 2020

I had an issue with the last event being fired being a mouseover event. I switched the mouseover to mouseenter and mouseout to mouseleave which solved it. Any drawbacks to this method? It also limits the amount of events firing as it doesn't fire on child elements.

@Theo-flux
Copy link

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?

@Theo-flux
Copy link

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