# useBroadcastChannel
Package: @mantine/hooks
Import: import { useBroadcastChannel } from '@mantine/hooks';

## Usage

`use-broadcast-channel` sends messages between tabs, windows, iframes and workers of the same origin
with the [BroadcastChannel API](https://developer.mozilla.org/en-US/docs/Web/API/BroadcastChannel).
Use it to sync logout, theme or cart between tabs.

Open this page in a second browser tab to see the reactions synced between tabs:

```tsx
import { useBroadcastChannel } from '@mantine/hooks';
import { Badge, Button, Group, Paper, Text } from '@mantine/core';

const reactions = ['👋', '🎉', '☕', '🚀'];

function Panel({ label }: { label: string }) {
  const { supported, data, post } = useBroadcastChannel<string>('mantine-demo-channel');

  return (
    <Paper withBorder p="md" flex={1}>
      <Group justify="space-between" mb="md">
        <Text fw={500}>{label}</Text>
        <Badge color={supported ? 'teal' : 'red'} variant="light">
          {supported ? 'supported' : 'unsupported'}
        </Badge>
      </Group>

      <Text size="sm" c="dimmed">Last received</Text>
      <Text fz={32}>{data ?? '—'}</Text>

      <Group mt="md" gap="xs">
        {reactions.map((reaction) => (
          <Button key={reaction} variant="default" onClick={() => post(reaction)}>
            {reaction}
          </Button>
        ))}
      </Group>
    </Paper>
  );
}

// Both panels create their own channel with the same name, so a message posted
// from one is delivered to the other (but never back to the sender). Open this
// page in a second browser tab to see the reactions sync across tabs as well.
function Demo() {
  return (
    <Group align="stretch" grow>
      <Panel label="Tab A" />
      <Panel label="Tab B" />
    </Group>
  );
}
```


## Definition

```tsx
interface UseBroadcastChannelReturnValue<T> {
  /** `true` if the BroadcastChannel API is available in the current environment */
  supported: boolean;

  /** The underlying BroadcastChannel instance, `null` on the server and after `close` */
  channel: BroadcastChannel | null;

  /** Data of the last message received from another context, `undefined` until a message arrives */
  data: T | undefined;

  /** Posts a message to all other contexts subscribed to the same channel name */
  post: (data: T) => void;

  /** The last `messageerror` event, `null` otherwise */
  error: MessageEvent | null;

  /** Closes the channel manually, after which `post` becomes a no-op until it is recreated */
  close: () => void;
}

function useBroadcastChannel<T = any>(name: string): UseBroadcastChannelReturnValue<T>;
```

## Sending and receiving

Call `post` to send a message to every other context with the same channel name.
`data` updates whenever another context posts a message:

```tsx
import { useBroadcastChannel } from '@mantine/hooks';

function Demo() {
  const { data, post } = useBroadcastChannel<string>('notifications');

  return (
    <button type="button" onClick={() => post('Hello from another tab')}>
      Last message: {data ?? 'none'}
    </button>
  );
}
```

## Self-exclusion

A message is not delivered back to the tab that sent it, `data` is never updated by your own `post` calls.
To update the sending tab, change its local state in addition to calling `post`:

```tsx
import { useState } from 'react';
import { useBroadcastChannel } from '@mantine/hooks';

function Demo() {
  const [value, setValue] = useState('light');
  const { post } = useBroadcastChannel<string>('theme');

  const setTheme = (theme: string) => {
    setValue(theme); // update the current tab
    post(theme); // update every other tab
  };

  // ...
}
```

## Structured data

`post` accepts any [structured-cloneable](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm)
value, for example objects, arrays or dates. Pass a type argument to type the message data:

```tsx
import { useBroadcastChannel } from '@mantine/hooks';
import { ColorSwatch, Group, Paper, Stack, Text } from '@mantine/core';

interface Settings {
  color: string;
  updatedAt: number;
}

const swatches = ['#fa5252', '#7950f2', '#4c6ef5', '#12b886', '#fab005'];

// post() accepts any structured-cloneable value, so there is no need to
// JSON.stringify the payload — objects are transferred as-is.
function Panel({ label }: { label: string }) {
  const { data, post } = useBroadcastChannel<Settings>('mantine-settings-channel');

  return (
    <Paper withBorder p="md" flex={1}>
      <Text fw={500} mb="md">{label}</Text>

      <Group mb="md">
        {swatches.map((color) => (
          <ColorSwatch
            key={color}
            color={color}
            style={{ cursor: 'pointer' }}
            onClick={() => post({ color, updatedAt: Date.now() })}
          />
        ))}
      </Group>

      <Stack gap={4}>
        <Text size="sm" c="dimmed">Received settings</Text>
        {data ? (
          <Group gap="xs">
            <ColorSwatch color={data.color} size={20} />
            <Text size="sm">{data.color}</Text>
          </Group>
        ) : (
          <Text size="sm">—</Text>
        )}
      </Stack>
    </Paper>
  );
}

function Demo() {
  return (
    <Group align="stretch" grow>
      <Panel label="Tab A" />
      <Panel label="Tab B" />
    </Group>
  );
}
```


## Handling errors

`error` holds the last `messageerror` event, emitted when a received message cannot be deserialized:

```tsx
import { useBroadcastChannel } from '@mantine/hooks';

function Demo() {
  const { error } = useBroadcastChannel('data-sync');

  if (error) {
    return <div>Failed to read a broadcast message</div>;
  }

  // ...
}
```

## Closing the channel

The channel is closed automatically on unmount or when the `name` changes.
Call `close` to close it earlier, after that `post` does nothing:

```tsx
import { Button } from '@mantine/core';
import { useBroadcastChannel } from '@mantine/hooks';

function Demo() {
  const { close } = useBroadcastChannel('notifications');

  return <Button onClick={close}>Stop receiving notifications</Button>;
}
```

## Server-side rendering

On the server and in browsers without the BroadcastChannel API, `supported` is `false` and `post` does nothing.

## Difference from use-local-storage

[use-local-storage](https://alpha.mantine.dev/llms/hooks-use-local-storage.md) also syncs state across tabs, but it persists the value.
`use-broadcast-channel` does not store anything, use it for messaging, including with workers and iframes.

## Definition of exported types

`UseBroadcastChannelReturnValue` type is exported from the `@mantine/hooks` package, you can
import it in your application:

```tsx
import type { UseBroadcastChannelReturnValue } from '@mantine/hooks';
```
