# useBroadcastChannel

Sends and receives messages between tabs, windows, and iframes of the same origin, over a `BroadcastChannel`.

Opens the channel on mount and closes it on unmount. Always calls the latest `onMessage`. The sender does not receive its own messages. Messages must be structured-cloneable (plain objects, arrays, dates, maps; no functions or class instances). Nothing happens on the server; `post` does nothing until mounted.

## Import

```ts
import { useBroadcastChannel } from '@vincent.ri/react-tils'
// or only this hook
import { useBroadcastChannel } from '@vincent.ri/react-tils/useBroadcastChannel'
```

## Usage

```ts
const post = useBroadcastChannel<{ type: 'logout' }>('auth', (message) => {
  if (message.type === 'logout') router.replace('/login')
})
const logout = async () => {
  await api.logout()
  post({ type: 'logout' })
}
```

## When to use it

Telling other tabs about an event, e.g. "logged out", "cart updated", or "this tab is now the leader".

## When not to

You are syncing a value that should also survive a reload; use `useLocalStorage`, which syncs across tabs too. For messages to a specific window or iframe, use `postMessage`.

## API

```ts
function useBroadcastChannel<T = unknown>(name: string, onMessage?: (message: T, event: MessageEvent<T>) => void): (message: T) => void
```

| Parameter | Description |
| --- | --- |
| `name` | Channel name. Every tab using the same name shares the channel. |
| `onMessage` | Called with each message from other tabs. Can change every render. |

**Returns** `post(message)`, stable for the life of the component.

## Browser support

Works in all modern browsers.

---

214 B minified and brotlied
Source: https://github.com/vincentri/react-tils/blob/main/src/useBroadcastChannel.ts
Docs page: https://vincentri.github.io/react-tils/hooks/useBroadcastChannel/
Previous: [useSearchParam](https://vincentri.github.io/react-tils/hooks/useSearchParam.md)
Next: [useOnline](https://vincentri.github.io/react-tils/hooks/useOnline.md)
