Skip to Content
vitus·labs
Hooks

Event Hooks

useHover, useFocus, useFocusTrap, useKeyboard, useEventListener, useCopyToClipboard.

useHover

Simple hover-state hook. Returns boolean and stable handler functions ready to spread onto elements.

import { useHover } from '@vitus-labs/hooks'

function HoverCard() {
  const { hover, onMouseEnter, onMouseLeave } = useHover()

  return (
    <div
      onMouseEnter={onMouseEnter}
      onMouseLeave={onMouseLeave}
      style={{
        background: hover ? '#f0f0f0' : 'white',
        transform: hover ? 'scale(1.02)' : 'scale(1)',
        transition: 'all 0.2s',
      }}
    >
      Hover me
    </div>
  )
}

Parameters

ParameterTypeDefaultDescription
initialValuebooleanfalseInitial hover state

Returns

PropertyTypeDescription
hoverbooleanCurrent hover state
onMouseEnter() => voidStable callback → sets hover = true
onMouseLeave() => voidStable callback → sets hover = false

Web only — not exported on React Native (no RN component fires onMouseEnter/onMouseLeave; use Pressable's onHoverIn/onHoverOut).


useFocus

Simple focus-state hook for form elements.

import { useFocus } from '@vitus-labs/hooks'

function StyledInput() {
  const { focused, onFocus, onBlur } = useFocus()

  return (
    <div style={{ borderColor: focused ? 'blue' : '#ccc' }}>
      <input onFocus={onFocus} onBlur={onBlur} placeholder="Type here..." />
    </div>
  )
}

Parameters

ParameterTypeDefaultDescription
initialValuebooleanfalseInitial focus state

Returns

PropertyTypeDescription
focusedbooleanCurrent focus state
onFocus() => voidStable callback → sets focused = true
onBlur() => voidStable callback → sets focused = false

Web only — not exported on React Native (use the RN component's own onFocus/onBlur props).


useFocusTrap

Traps keyboard focus within a container. Tab cycles forward through focusable elements, Shift+Tab cycles backward. When reaching the last element, focus wraps to the first. With autoFocus (the default), focus moves into the container on enable and is restored to the previously focused element on disable — matching the WAI-ARIA dialog pattern. Pair with useScrollLock for full modal accessibility.

import { useFocusTrap } from '@vitus-labs/hooks'

function Dialog({ isOpen, onClose }) {
  const dialogRef = useRef<HTMLDivElement>(null)
  useFocusTrap(dialogRef, isOpen)

  if (!isOpen) return null

  return (
    <div ref={dialogRef} role="dialog" aria-modal="true">
      <h2>Dialog Title</h2>
      <input placeholder="Name" />
      <input placeholder="Email" />
      <button onClick={onClose}>Close</button>
      {/* Tab cycles between the 3 focusable elements above */}
    </div>
  )
}

Parameters

ParameterTypeDefaultDescription
ref{ current: HTMLElement | null }—Container ref (a container that mounts later is picked up)
enabledbooleantrueEnable/disable trap
options.autoFocusbooleantrueFocus the first focusable element (or the container itself when there is none) on enable, and restore previous focus on disable

Focusable Elements

The trap targets these elements within the container:

  • a[href]
  • button:not([disabled])
  • input:not([disabled])
  • select:not([disabled])
  • textarea:not([disabled])
  • [contenteditable]:not([contenteditable="false"])
  • video[controls], audio[controls]
  • summary
  • [tabindex]:not([tabindex="-1"])

Elements with aria-disabled="true" are skipped. The list is cached and refreshed by a MutationObserver when children are added/removed or focusability attributes (disabled, tabindex, aria-disabled, contenteditable, href, hidden) change — not on every keypress.

Focus cannot escape (2.9): when the container has no focusable children, Tab is always blocked; when focus is on the container itself or outside the trapped list, Tab moves to the first element and Shift+Tab to the last.


useKeyboard

Listens for a specific keyboard key press on the window.

import { useKeyboard } from '@vitus-labs/hooks'

function Modal({ isOpen, onClose }) {
  useKeyboard('Escape', () => {
    if (isOpen) onClose()
  })

  // ...
}

function App() {
  useKeyboard('/', () => {
    document.querySelector<HTMLInputElement>('#search')?.focus()
  })

  // ...
}

Parameters

ParameterTypeDescription
keystringKey name to listen for (e.g., 'Escape', 'Enter', 'a')
handler(event: KeyboardEvent) => voidCallback when key is pressed

Matches against event.key. Always calls the latest handler (no stale closures). Attached to window keydown event. On React Native this hook is a no-op.


useEventListener

Subscribe to a DOM event with correct typing and cleanup. The handler is held in a ref, so the registered listener stays stable even when you pass a fresh closure every render.

import { useEventListener } from '@vitus-labs/hooks'

function Popover({ onClose }) {
  const ref = useRef<HTMLDivElement>(null)

  // Defaults to window
  useEventListener('keydown', (e) => {
    if (e.key === 'Escape') onClose()
  })

  // Ref target + options
  useEventListener('scroll', () => onClose(), ref, { passive: true })

  return <div ref={ref}>…</div>
}

Parameters

ParameterTypeDefaultDescription
eventK extends keyof WindowEventMap—Event name
handler(e: WindowEventMap[K]) => void—Event handler (latest one is always called)
targetEventTarget | { current: EventTarget | null } | nullwindowElement, ref, or null to skip
optionsAddEventListenerOptions | boolean—Listener options (capture, passive, once, signal)

Ref targets are tracked after every commit, so an element that mounts later still gets the listener. The effect depends on the individual option values rather than the options object, so an inline { passive: true } no longer detaches/re-attaches the listener on every render (2.9).


useCopyToClipboard

Copy text to the clipboard with a transient "copied" flag.

import { useCopyToClipboard } from '@vitus-labs/hooks'

function CopyButton({ text }) {
  const [copied, copy] = useCopyToClipboard()

  return (
    <button onClick={() => copy(text)}>
      {copied ? 'Copied' : 'Copy'}
    </button>
  )
}

Parameters

ParameterTypeDefaultDescription
resetMsnumber2000Time after which copied resets to false. 0 disables the auto-reset

Returns

readonly [copied: boolean, copy: (text: string) => Promise<boolean>, reset: () => void]

IndexNameDescription
0copiedtrue after a successful copy, until reset
1copyCopies text; resolves to true on success
2resetClear copied and the pending reset timer

Uses the async Clipboard API (navigator.clipboard.writeText) and falls back to document.execCommand('copy') when the API is unavailable or rejects (insecure origin, missing user gesture, permissions). The reset timer is cleaned up on unmount.

Edit on GitHub

Last updated on

On this page