EventIntermediateBrowser APIshooks/events/useDocumentEvent.ts

useDocumentEvent

Listen on document.

Import

TypeScript
import { useDocumentEvent } from '@/hooks';

API

Signature

useDocumentEvent(event, handler, options?)

When to use

Use useDocumentEvent instead of re-implementing the same pattern in multiple components.

SSR / Next.js

No-ops until document/window exist.

Live playground

Edit the example and see it run against the real @/hooks package in this app.

Live playgroundEdit · run with real @/hooks · useDocumentEvent
Editor
function VisibilityLog() {
  useDocumentEvent('visibilitychange', () => {
    console.log(document.visibilityState);
  });
  return null;
}
Preview

Implementation source

Full library source for useDocumentEvent — copy into your project when you are not installing a package yet.

hooks/events/useDocumentEvent.ts
import { useEventListener, type UseEventListenerOptions } from './useEventListener';
import type { BasicTarget } from '../utility/getTargetElement';

/** Subscribe to a document event. */
export function useDocumentEvent<K extends keyof DocumentEventMap>(
  eventName: K,
  handler: (event: DocumentEventMap[K]) => void,
  options?: UseEventListenerOptions,
): void {
  useEventListener(
    eventName,
    handler as (event: Event) => void,
    typeof document !== 'undefined'
      ? (document as unknown as BasicTarget)
      : undefined,
    options,
  );
}

Copy-paste example

useDocumentEvent.example.tsx
'use client';

import { useDocumentEvent } from '@/hooks';

export function VisibilityLog() {
  useDocumentEvent('visibilitychange', () => {
    console.log(document.visibilityState);
  });
  return null;
}

Production checklist

  • Called only from Client Components or other custom hooks
  • Type parameters filled in (e.g. useFetch<User[]>)
  • Tip: Pass all relevant refs to useClickOutside (trigger + panel). Prefer useLatest for handlers.
  • Source of truth: open hooks/events/useDocumentEvent.ts for implementation details