useHover

React hook to track when an element is being hovered over.

Add the hook via the CLI:

npx @novajslabs/cli add useHover

Or copy and paste the code into your project:

import { useState, RefObject, useEffect } from 'react'

export const useHover = (ref: RefObject<HTMLElement>) => {
  const [isHovered, setIsHovered] = useState<boolean>(false)

  const handleMouseEnter = () => setIsHovered(true)
  const handleMouseLeave = () => setIsHovered(false)

  useEffect(() => {
    const node = ref.current

    if (node) {
      node.addEventListener('mouseenter', handleMouseEnter)
      node.addEventListener('mouseleave', handleMouseLeave)

      return () => {
        node.removeEventListener('mouseenter', handleMouseEnter)
        node.removeEventListener('mouseleave', handleMouseLeave)
      }
    }
  }, [ref])

  return isHovered
}

React 16.8 or higher

  • Name
    ref
    Type
    HTMLElement
    Required
    required
    Description

    The HTML element to track.

  • Name
    isHovered
    Type
    boolean
    Description

    Indicates whether the HTML element is currently hovered (true) or not (false).

import { useRef } from 'react'
import { useHover } from './hooks/useHover'

const App = () => {
  const boxRef = useRef<HTMLDivElement>(null)
  const isHovered = useHover(boxRef)

  return (
    <div ref={boxRef} style={{ padding: '20px', border: '1px solid black' }}>
      {isHovered ? 'Hovering...' : 'Not hovering'}
    </div>
  )
}

export default App

Here are some use cases where this React hook is useful:

  • Displaying tooltip on hover
  • Highlighting table row on hover
  • Playing a video preview on hover
  • Showing an overlay on card hover