All hooks / Storage and URL

useBroadcastChannel

214 B minified and brotliedSourceMarkdown✓ Works in all modern browsers

Sends and receives messages between tabs, windows, and iframes of the same origin, over a BroadcastChannel.

Opens the channel on mount and closes it on unmount. Always calls the latest onMessage. The sender does not receive its own messages. Messages must be structured-cloneable (plain objects, arrays, dates, maps; no functions or class instances). Nothing happens on the server; post does nothing until mounted.

Import

import { useBroadcastChannel } from '@vincent.ri/react-tils'
// or only this hook
import { useBroadcastChannel } from '@vincent.ri/react-tils/useBroadcastChannel'

Usage

const post = useBroadcastChannel<{ type: 'logout' }>('auth', (message) => {
  if (message.type === 'logout') router.replace('/login')
})
const logout = async () => {
  await api.logout()
  post({ type: 'logout' })
}

Live demo

Open this page in two tabs, then send.

received: nothing yet

When to use it

Telling other tabs about an event, e.g. "logged out", "cart updated", or "this tab is now the leader".

When not to

You are syncing a value that should also survive a reload; use useLocalStorage, which syncs across tabs too. For messages to a specific window or iframe, use postMessage.

API

function useBroadcastChannel<T = unknown>(name: string, onMessage?: (message: T, event: MessageEvent<T>) => void): (message: T) => void
ParameterDescription
nameChannel name. Every tab using the same name shares the channel.
onMessageCalled with each message from other tabs. Can change every render.

Returns post(message), stable for the life of the component.

Browser support

UsesChromeEdgeFirefoxSafariChrome AndroidSafari iOS
BroadcastChannelWidely available54+79+38+15.4+54+15.4+

First version with support, from MDN's compatibility data (web-features 3.42.0, @mdn/browser-compat-data 8.1.5).