EventIntermediateBrowser APIshooks/events/useWindowEvent.ts

useWindowEvent

Listen on window.

Import

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

API

Signature

useWindowEvent(event, handler, options?)

When to use

Use useWindowEvent 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 · useWindowEvent
Editor
function OnlineBadge() {
  const [online, setOnline] = useState(true);
  useWindowEvent('online', () => setOnline(true));
  useWindowEvent('offline', () => setOnline(false));
  return <span>{online ? 'Online' : 'Offline'}</span>;
}
Preview

Implementation source

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

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

/** Subscribe to a window event. */
export function useWindowEvent<K extends keyof WindowEventMap>(
  eventName: K,
  handler: (event: WindowEventMap[K]) => void,
  options?: UseEventListenerOptions,
): void {
  useEventListener(
    eventName,
    handler as (event: Event) => void,
    window as unknown as BasicTarget,
    options,
  );
}

Copy-paste example

useWindowEvent.example.tsx
'use client';

import { useState } from 'react';
import { useWindowEvent } from '@/hooks';

export function OnlineBadge() {
  const [online, setOnline] = useState(true);
  useWindowEvent('online', () => setOnline(true));
  useWindowEvent('offline', () => setOnline(false));
  return <span>{online ? 'Online' : 'Offline'}</span>;
}

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/useWindowEvent.ts for implementation details