Skip to Content
ohooks

useFocus

Tracks and controls the focus state of a target DOM element, with optional :focus-visible filtering.

Loading preview...

The useFocus hook monitors focus and blur events on a target DOM element, supports initial autofocus and :focus-visible filtering, and provides programmatic focus and blur helpers.

Installation

pnpm dlx shadcn@latest add https://ohooks.vercel.app/r/useFocus.json

Usage

Examples

Programmatic Focus Control

Use focus() and blur() to move focus to an input from external buttons or shortcuts.

Keyboard-Only Focus Ring (focusVisible)

Enable focusVisible: true so isFocused only turns true when the element matches :focus-visible (such as via Tab navigation).

API Reference

UseFocusOptions

Configuration options for initial focus and :focus-visible matching.

Property
Specification
focusVisible?
uniondefault:false
Only mark as focused when the element matches :focus-visible
onFocus?
function
Callback fired when the element receives focus
onBlur?
function
Callback fired when the element loses focus

UseFocusReturn

Focus state and programmatic control methods returned by the hook.

Property
Specification
isFocused
union
Whether the target element is currently focused
focus
function
Programmatically focuses the target element
blur
function
Programmatically removes focus from the target element