Browser APIs
useBroadcastChannel
About
A React hook that provides a clean interface to the Broadcast Channel API for cross-tab/window communication. This hook allows you to send and receive messages between different browser tabs, windows, or workers of the same origin, enabling real-time synchronization across multiple instances of your application.
Examples
Basic cross-tab communication
Real-time counter synchronization
Shopping cart synchronization
Arguments
Argument | Type | Description | Default |
---|---|---|---|
channelName | string | The name of the broadcast channel to connect to | - |
options | UseBroadcastChannelOptions<T> | Optional configuration object |
Options
Option | Type | Description | Default |
---|---|---|---|
onMessage | (data: T) => void | Callback function called when a message is received | undefined |
onError | (error: Event) => void | Callback function called when an error occurs | undefined |
Returns
Returns an object with the following properties:
Return value | Type | Description | Default |
---|---|---|---|
postMessage | (data: T) => void | Function to send a message to the broadcast channel | - |
close | () => void | Function to manually close the broadcast channel | - |
isSupported | boolean | Whether the BroadcastChannel API is supported | false |
TypeScript Support
Browser Support
- Chrome: 54+
- Firefox: 38+
- Safari: 15.4+
- Edge: 79+
The hook includes built-in support detection and will gracefully handle unsupported browsers by setting isSupported
to false
.
Performance Notes
- Messages are automatically serialized/deserialized using the structured clone algorithm
- The hook automatically cleans up event listeners when the component unmounts
- Multiple hooks with the same channel name will all receive the same messages
- Consider using unique channel names for different features to avoid message conflicts