Repo of the Day
GuptaSiddhant/react-broadcast-channel
Published: Nov 21, 2024
Open repository ↗React hooks for accessing web broadcast channel API.
Summary
use-broadcast-channel is a small TypeScript library that wraps the browser's native Broadcast Channel API in React hooks. It exposes useBroadcastChannel for sending and receiving messages and useBroadcastState for keeping a useState-like value in sync across browser contexts. The package is published under the MIT license and targets any React app that needs same-origin cross-tab communication.
What it is useful for
The library helps when one part of a React application needs to notify other tabs, windows, iframes, or workers on the same origin without a server round-trip. The README's examples illustrate syncing a counter or a user identifier between two open tabs of the same app. Because the underlying API is same-origin only, it suits client-side state that should stay consistent across views opened by the same user, such as a logout signal, a theme change, or a shared form draft, rather than cross-domain messaging.
How engineers can use it
Installation is documented for two package managers: npm install use-broadcast-channel or yarn add use-broadcast-channel.
The README documents three usage patterns for useBroadcastChannel:
- Read-only:
useBroadcastChannel("userId", (e) => alert(e.data))subscribes to a channel and runs a callback on each message. - Write-only:
const postUserId = useBroadcastChannel("userId")returns a poster function used in an event handler. - Read-and-write: pass both the channel name and a listener, then call the returned function to publish, e.g.
postUserId("ABC123")from a button click.
useBroadcastState mirrors the React.useState API and broadcasts each update. The documented example is a counter whose setCount((prev) => prev + 1) calls stay in sync across tabs that share the same channel name.
TypeScript users should note the default message type is string; passing a generic such as useBroadcastChannel<number>(...) overrides it for numeric or other payloads.
One documented limitation: browsers without native Broadcast Channel support require the optional broadcastchannel-polyfill peer dependency, which the README links to but does not auto-install or document how to wire up. The README also does not describe any explicit unsubscribe or teardown behavior beyond what React's hook lifecycle provides, so engineers building production flows should consult it directly for those details.