useHover
Here's an example of a custom hook that uses the useState
, useRef
, and useEffect
Hooks to detect when an element is being hovered:
import { useState, useRef, useEffect } from 'react'
function useHover() {
const [isHovered, setIsHovered] = useState(false)
const ref = useRef(null)
function handleMouseOver() {
setIsHovered(true)
}
function handleMouseOut() {
setIsHovered(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])
return [ref, isHovered]
}
This custom hook returns an array with two values: a ref
and a boolean value representing whether the element is being hovered. We use the useState
Hook to initialize the isHovered
state, the useRef
Hook to create a ref for the element, and the useEffect
Hook to add event listeners to the element. When the element is hovered over or out of, we update the isHovered
state accordingly.
To use this custom hook, you would simply call it in your functional component:
function MyComponent() {
const [ref, isHovered] = useHover()
return (
<div ref={ref}>{isHovered ? <p>Hovered!</p> : <p>Not hovered!</p>}</div>
)
}
In this example, we call the useHover
hook to detect when an element is being hovered over and use it to display a message accordingly. By using the useHover
Hook, we can easily detect when an element is being hovered over and apply custom styles or behavior.