All hooks / Storage and URL
useBroadcastChannel
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.
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| Parameter | Description |
|---|---|
name | Channel name. Every tab using the same name shares the channel. |
onMessage | Called with each message from other tabs. Can change every render. |
Returns post(message), stable for the life of the component.
Browser support
| Uses | Chrome | Edge | Firefox | Safari | Chrome Android | Safari iOS |
|---|---|---|---|---|---|---|
| BroadcastChannelWidely available | 54+ | 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).