Use the Provider
When several components need the same channel, opening it once at the top of the tree beats repeating the hook. <BroadcastProvider> calls useBroadcastChannel internally and shares the result through context; descendants read it with useBroadcastProvider().
import { BroadcastProvider, useBroadcastProvider } from 'react-broadcast-sync';
function App() { return ( <BroadcastProvider channelName="app" options={{ namespace: 'v1' }}> <Notifications /> <PresenceIndicator /> </BroadcastProvider> );}
function PresenceIndicator() { const { ping, isPingInProgress } = useBroadcastProvider(); // same actions as the hook}| Prop | Type | Required | Description |
|---|---|---|---|
channelName |
string |
yes | Channel name. Combined with options.namespace if set. |
options |
BroadcastOptions |
no | The same options object the hook takes. |
children |
ReactNode |
yes | The subtree that shares the channel. |
- Everything inside the provider shares one connection. Components can still send different message types over it (
registeredTypeshelps keep that tidy). useBroadcastProvider()throws if noBroadcastProvideris above it in the tree.- The provider accepts the full options object, including
sourceName,registeredTypes, andonMessage.onMessageset here fires for the whole subtree’s incoming traffic. - Components that need a different channel can still call
useBroadcastChanneldirectly, inside or outside the provider.
See Hook or provider? for help choosing, and the provider demo for a working app.
