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
| Parameter | Type | Default | Description |
|---|---|---|---|
initialValue | boolean | false | Initial hover state |
Returns
| Property | Type | Description |
|---|---|---|
hover | boolean | Current hover state |
onMouseEnter | () => void | Stable callback → sets hover = true |
onMouseLeave | () => void | Stable 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
| Parameter | Type | Default | Description |
|---|---|---|---|
initialValue | boolean | false | Initial focus state |
Returns
| Property | Type | Description |
|---|---|---|
focused | boolean | Current focus state |
onFocus | () => void | Stable callback → sets focused = true |
onBlur | () => void | Stable 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
| Parameter | Type | Default | Description |
|---|---|---|---|
ref | { current: HTMLElement | null } | — | Container ref (a container that mounts later is picked up) |
enabled | boolean | true | Enable/disable trap |
options.autoFocus | boolean | true | Focus 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
| Parameter | Type | Description |
|---|---|---|
key | string | Key name to listen for (e.g., 'Escape', 'Enter', 'a') |
handler | (event: KeyboardEvent) => void | Callback 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
| Parameter | Type | Default | Description |
|---|---|---|---|
event | K extends keyof WindowEventMap | — | Event name |
handler | (e: WindowEventMap[K]) => void | — | Event handler (latest one is always called) |
target | EventTarget | { current: EventTarget | null } | null | window | Element, ref, or null to skip |
options | AddEventListenerOptions | 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
| Parameter | Type | Default | Description |
|---|---|---|---|
resetMs | number | 2000 | Time after which copied resets to false. 0 disables the auto-reset |
Returns
readonly [copied: boolean, copy: (text: string) => Promise<boolean>, reset: () => void]
| Index | Name | Description |
|---|---|---|
| 0 | copied | true after a successful copy, until reset |
| 1 | copy | Copies text; resolves to true on success |
| 2 | reset | Clear 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.
Last updated on