useBroadcastChannel
useBroadcastChannel is a hook that allows you to use the BroadcastChannel API in your components.
useBroadcastChannel wraps the BroadcastChannel API to enable simple messaging between browsing contexts (tabs, windows, iframes) on the same origin. It returns an object containing the current data, a post function for sending messages, connection status, error state, and a close function. The hook automatically manages the channel lifecycle and cleans up on unmount.
When to Use
- Synchronizing state across multiple open tabs of the same application (e.g., theme changes, logout events)
- Broadcasting real-time updates to all open instances of your app without a server
- Coordinating actions between iframes or popup windows on the same origin
Notes
- SSR-safe: Returns
isSupported: falseand no-op functions during server-side rendering. NoBroadcastChannelconstructor is called on the server. - Browser support: Supported in all modern browsers. Check
isSupportedbefore relying on channel functionality. - Same-origin only: The BroadcastChannel API only works between browsing contexts of the same origin.
Usage
Live Editor
function Demo() { const { isSupported, data, post, error,timeStamp } = useBroadcastChannel({ name: "reactuse-demo-channel", }); const [message, setMessage] = useState(""); useEffect(() => { if (isSupported) { alert(data); } }, [data]); return ( <div> <p>Supported: {JSON.stringify(isSupported)}</p> <p>Please open this page in at least two tabs</p> <p> <b>Channel:</b> reactuse-demo-channel </p> <p> <b>Message:</b> {data}<br/> <b>TimeStamp:</b> {timeStamp} </p> <input value={message} onChange={(event) => { setMessage(event.currentTarget.value); }} /> <button onClick={() => post(message)} style={{ cursor: isSupported ? "pointer" : "not-allowed", }} > Send </button> {error && <p>Error: {error.message}</p>} </div> ); };
Result
API
UseBroadcastChannelOptions
| Property | Description | Type | DefaultValue |
|---|---|---|---|
| name | channel name | string (Required) | - |
UseBroadcastChannel
Returns
UseBroadcastChannelReturn<D, P>
Arguments
| Argument | Description | Type | DefaultValue |
|---|---|---|---|
| options | options | UseBroadcastChannelOptions (Required) | - |
UseBroadcastChannelReturn
| Property | Description | Type | DefaultValue |
|---|---|---|---|
| isSupported | is supported | boolean (Required) | - |
| channel | channel | BroadcastChannel | undefined (Required) | - |
| data | data | D | undefined (Required) | - |
| post | post data | (data: P) => void (Required) | - |
| close | close | () => void (Required) | - |
| error | error | Event | null (Required) | - |
| isClosed | is closed | boolean (Required) | - |
| timeStamp | timestamp | number (Required) | - |