Loading...
Please waitLoading...
Please waitShare live messages across tabs with a small React wrapper around the BroadcastChannel API, including message state, cleanup, and error handling.
pnpm dlx uselab@latest add use-broadcast-channel
import { useBroadcastChannel } from "@/hooks/use-broadcast-channel"
export function PresencePing() {
const { lastMessage, postMessage } =
useBroadcastChannel<string>("presence-room")
return (
<div className="space-y-2">
<button onClick={() => postMessage("editor-opened")}>Send ping</button>
<p>{lastMessage || "No messages yet"}</p>
</div>
)
}useBroadcastChannel(name, options?)| Name | Type | Description | Optional |
|---|---|---|---|
name | string | Channel name shared by every tab that should communicate. | No |
options | UseBroadcastChannelOptions<T> | Optional callbacks for received messages and receive errors. | Yes |
The hook returns an object { isSupported, isClosed, lastMessage, error, postMessage, close }:
| Name | Type | Description |
|---|---|---|
isSupported | boolean | Whether BroadcastChannel exists in the current environment. |
isClosed | boolean | Whether the current channel instance has been closed. |
lastMessage | T | null | Most recent received message payload. |
error | Error | null | Last send or receive error. |
postMessage | (message: T) => boolean | Sends a message and returns whether dispatch succeeded. |
close | () => void | Closes the channel and detaches message handlers. |
interface UseBroadcastChannelOptions<T> {
onMessage?: (data: T) => void
onMessageError?: (event: Event) => void
}onMessage: Runs whenever a message is received on the active channel.onMessageError: Runs when the browser reports a message deserialization or delivery failure.BroadcastChannel is best for same-origin tabs and windows. It does not replace server pub/sub for cross-device communication.Sender state
Connected
Last received
Nothing received yet
Open the same page in another tab with the same channel name to see real cross-tab delivery.