useDocumentEventListener
Attaches a document event listener and removes it when the component unmounts.
About
useDocumentEventListener listens for a named event on the browser document. Use it for document-wide events such as selectionchange or visibilitychange; use an element-scoped listener when a local target is sufficient.
Example
import { useState } from "react";
import { useDocumentEventListener } from "rooks";
export default function SelectionCounter() {
const [changes, setChanges] = useState(0);
useDocumentEventListener("selectionchange", () => {
setChanges((count) => count + 1);
});
return <p>Selection changes observed: {changes}</p>;
}Parameters
eventName: a key fromDocumentEventMap.callback: called with the native document event. The hook always invokes the latest callback.listenerOptions: optionalboolean | AddEventListenerOptions; defaults to{}. It supportscapture,once,passive,signal, or the capture boolean shorthand.isLayoutEffect: optional boolean; defaults tofalse. Set it totrueonly when the listener must be synchronized during the layout-effect phase.
Return value
The hook returns void.
Behavior and lifecycle
The listener is attached after commit, or during the layout-effect phase when isLayoutEffect is true. A changed target, event name, or listener option replaces the existing subscription. Callback changes do not require a new native listener. Cleanup removes the active listener when the configuration changes or the component unmounts.
Compatibility and accessibility
During server rendering there is no document target, so the hook performs no subscription. Browser support and event semantics depend on the chosen document event. Global listeners do not provide user feedback by themselves; expose any resulting state through appropriate visible text or ARIA semantics.
Related
- useWindowEventListener listens on
window. - useEventListenerRef targets an element through a callback ref.
- SSR and browser APIs covers client boundaries and fallbacks.