useActiveElement
Get a reactive reference to the currently focused element in the document.
useActiveElement
is used to get the currently focused element in the document.
If you don't need to provide a custom document
/ shadowRoot
, you can use the activeElement
state instead, as it provides a simpler API.
This utility behaves similarly to document.activeElement
but with additional features such as:
- Updates synchronously with DOM focus changes
- Returns
null
when no element is focused - Safe to use with SSR (Server-Side Rendering)
- Lightweight alternative to manual focus tracking
Demo
Currently active element: No active element found
Usage
Options
The following options can be passed via the first argument to useActiveElement
:
document
type: DocumentOrShadowRoot
The document or shadow root to track focus within.
default: document
window
type: Window
The window to use for focus tracking.
default: window