useHover

import { useHover } from 'react-laag';

When working with tooltips for instance, you sometimes want specific behavior regarding timing. If you show a tooltip immediately when the mouse enters the trigger element, the user may perceive the tooltip as annoying. That's why it's common to only show a tooltip after a certain time has passed while the user has been hovering over the trigger element. useHover is a hook which helps you control this kind of behavior.

useHover() comes in two variants (overloads): controlled vs. uncontrolled. They both share the same configuration, but differ in their return-type based on the configuration that is provided. When the onShow option is provided, useHover() will act controlled and will only return the HoverProps.

Type
(config?: UseHoverConfig): [boolean, HoverProps] | HoverProps
UseHoverConfig
details
delayEnter
number
Default
0

Amount of time in ms that should pass while hovering in order to show the layer.

delayLeave
number
Default
0

Amount of time in ms that should pass while user has left the element before the layer hides again .

hideOnScroll
boolean
Default
true

Determines whether the layer should hide when the user starts scrolling. Default is true.

onShow
(): void

Function that gets called when useHover has determined the layer should be shown.

onHide
(): void

Function that gets called when useHover has determined the layer should be hidden.

HoverProps
details
onMouseEnter
(event: MouseEvent): void
onMouseLeave
(event: MouseEvent): void

Example

Uncontrolled with <ToggleLayer />
function UseHoverExample() {
  const [show, hoverProps] = useHover({ delayEnter: 300, delayLeave: 200 });

  return (
    <ToggleLayer
      isOpen={show}
      renderLayer={({ layerProps }) =>
        isOpen ? <Layer {...layerProps} /> : null
      }
      // rest of props...
    >
      {({ triggerRef }) => (
        <div ref={triggerRef} {...hoverProps}>
          hover me!
        </div>
      )}
    </ToggleLayer>
  );
}
controlled with useToggleLayer()
function UseHoverExample() {
  const triggerRef = React.useRef();
  const [element, toggleLayerProps] = useToggleLayer(/* layer element here */);
  const hoverProps = useHover({
    delayEnter: 300,
    delayLeave: 200,
    onShow: () => toggleLayerProps.openFromRef(triggerRef),
    onHide: () => toggleLayerProps.close()
  });

  return (
    <>
      {element}
      <div ref={triggerRef} {...hoverProps}>
        hover me!
      </div>
    </>
  );
}