30% offEnding soon
useBroadcastChannelLoading saved progress…

useBroadcastChannel

The Broadcast Channel API lets same-origin browsing contexts exchange messages through a named channel. Implement a React hook that owns one BroadcastChannel, delivers incoming data to the latest callback, and closes the native resource when its name changes or the component unmounts. The hook must also remain safe in server rendering and browsers without the API.

Signature

function useBroadcastChannel(
  name: string,
  onMessage: (data: unknown, event: MessageEvent) => void
): {
  isSupported: boolean;
  postMessage: (data: unknown) => void;
}

Examples

const { result } = renderHook(() =>
  useBroadcastChannel('account', (data) => console.log(data))
);

// After the effect opens the channel:
result.current.isSupported; // true
result.current.postMessage({ type: 'signed-out' }); // undefined
// An incoming MessageEvent contains { type: 'theme', value: 'dark' }.
// Your callback receives both values, in this order:
onMessage({ type: 'theme', value: 'dark' }, originalMessageEvent);

Notes

  • Initial state — return isSupported: false during the first render; only an effect may construct the browser API.
  • Latest callback — a new onMessage identity must take effect without reopening the channel.
  • Stable sender — keep the returned postMessage function referentially stable. It forwards the exact value, returns the native result, and preserves native errors.
  • Lifecycle — a changed name removes the exact old listener and closes the old channel before opening the new one; unmount performs the same cleanup.
  • Unavailable API — if the constructor is missing or throws, remain unsupported and make postMessage throw a clear error.
  • Scope — do not serialize values, emulate delivery to the sending channel, handle messageerror, use localStorage, or define an application message protocol.