@r01al/use-broadcast-channel
v0.1.0
Published
A small React hook for type-safe messaging across browser tabs with BroadcastChannel.
Maintainers
Readme
useBroadcastChannel
useBroadcastChannel is a small, type-safe React hook for sending messages
between same-origin browser tabs, windows, frames, and workers through the
native BroadcastChannel
API.
Every channel name is automatically prefixed with r01al-ubc-. Passing
"cart", for example, opens the native channel "r01al-ubc-cart".
Installation
npm install @r01al/use-broadcast-channelReact 18 or newer is required as a peer dependency.
Usage
import { useState } from 'react';
import { useBroadcastChannel } from '@r01al/use-broadcast-channel';
type CartMessage = {
itemCount: number;
};
export function CartBadge() {
const [itemCount, setItemCount] = useState(0);
const postMessage = useBroadcastChannel<CartMessage>(
'cart',
(message) => setItemCount(message.itemCount),
);
return (
<button
onClick={() => {
const nextCount = itemCount + 1;
setItemCount(nextCount);
postMessage({ itemCount: nextCount });
}}
>
Cart ({itemCount})
</button>
);
}Open the component in two tabs. Clicking the button in one tab updates the
other tab through r01al-ubc-cart.
API
function useBroadcastChannel<Message>(
name: string,
subscription: (
message: Message,
event: MessageEvent<Message>,
) => void,
): (message: Message) => void;nameis the logical channel name. The package addsr01al-ubc-.subscriptionreceives the message data and the nativeMessageEvent.- The returned function sends a message to other contexts listening on the same channel.
The returned sender keeps the same identity across renders. The hook always
uses the latest subscription function, and changes to that function do not
reopen the native channel. Changing name does open a new channel.
Browser behavior
BroadcastChannel communication is limited to browsing contexts with the same
origin and compatible storage partition. A channel does not deliver a message
back to the same BroadcastChannel object, so update local state before or
alongside calling postMessage, as shown above.
The module can be server-rendered because it only opens the channel in a React
effect. Calling the returned sender requires a mounted browser component with
native BroadcastChannel support.
License
MIT
