Skip to Content
ohooks

useBroadcastChannel

Communicates between browser tabs, windows, or iframes of the same origin using the BroadcastChannel API.

Loading preview...

The useBroadcastChannel hook connects to a named BroadcastChannel so tabs, windows, and iframes sharing the same origin can broadcast and receive typed messages in real time.

Installation

pnpm dlx shadcn@latest add https://ohooks.vercel.app/r/useBroadcastChannel.json

Usage

Examples

Syncing Auth State Across Tabs

Use the onMessage callback to react immediately when another tab broadcasts an event such as signing out.

Closing the Channel

Call close to disconnect the tab from the channel when it no longer needs to receive updates.

API Reference

UseBroadcastChannelOptions

Callback options for handling incoming messages and deserialization errors.

Property
Specification
enabled?
uniondefault:true
Whether the broadcast channel subscription is active
onMessage?
function
Callback fired when a message is received on the channel
onMessageError?
function
Callback fired when a message cannot be deserialized

UseBroadcastChannelReturn

State and methods returned by the hook.

Property
Specification
isSupported
union
Whether the BroadcastChannel API is supported in the current environment
lastMessage
union
Most recent message data received from the channel
error
union
Latest message deserialization error event, or null
postMessage
function
Sends a message to all browsing contexts listening on the channel