use-broadcast-channel
Cross-tab and cross-context messaging with the BroadcastChannel API
Source
Package
Usage
use-broadcast-channel sends messages between tabs, windows, iframes and workers of the same origin
with the BroadcastChannel API.
Use it to sync logout, theme or cart between tabs.
Open this page in a second browser tab to see the reactions synced between tabs:
Tab A
Last received
—
Tab B
Last received
—
Definition
Sending and receiving
Call post to send a message to every other context with the same channel name.
data updates whenever another context posts a message:
Self-exclusion
A message is not delivered back to the tab that sent it, data is never updated by your own post calls.
To update the sending tab, change its local state in addition to calling post:
Structured data
post accepts any structured-cloneable
value, for example objects, arrays or dates. Pass a type argument to type the message data:
Tab A
Received settings
—
Tab B
Received settings
—
Handling errors
error holds the last messageerror event, emitted when a received message cannot be deserialized:
Closing the channel
The channel is closed automatically on unmount or when the name changes.
Call close to close it earlier, after that post does nothing:
Server-side rendering
On the server and in browsers without the BroadcastChannel API, supported is false and post does nothing.
Difference from use-local-storage
use-local-storage also syncs state across tabs, but it persists the value.
use-broadcast-channel does not store anything, use it for messaging, including with workers and iframes.
Definition of exported types
UseBroadcastChannelReturnValue type is exported from the @mantine/hooks package, you can
import it in your application: