Rooks
HooksEvent Handling

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 from DocumentEventMap.
  • callback: called with the native document event. The hook always invokes the latest callback.
  • listenerOptions: optional boolean | AddEventListenerOptions; defaults to {}. It supports capture, once, passive, signal, or the capture boolean shorthand.
  • isLayoutEffect: optional boolean; defaults to false. Set it to true only 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.

On this page