useBroadcastChannel
Hook to use broadcast channel.
See: Broadcast Channel API.
Demo
INFO
The component uses useBroadcastChannel hook to send a text in a broadcast channel
Loading demo…
Show source code
tsx
import { FormEvent } from "react";
import { useBroadcastChannel } from "../../../.."
export const UseBroadcastChannel = () => {
const [state, setState] = useBroadcastChannel<string>("react-tools");
return <div>
<h2>Open page on multiple tab to see how hook work</h2>
<p>State: {state}</p>
<form
onSubmit={(e: FormEvent<HTMLFormElement>) => {
e.preventDefault();
setState(((e.target as HTMLFormElement).elements.namedItem("text") as HTMLInputElement).value)
}}
>
<input name="text" type="text" />
<button type="submit">SEND</button>
</form>
</div>
}Types
UseBroadcastChannelProps
@templateT Type of the data exchanged on the channel.
Props accepted by useBroadcastChannel.
| Property | Type | Required | Description |
|---|---|---|---|
name | string | ✓ | broadcast channel name |
onMessage | (evt: MessageEvent<T>) => void | function that will be execute when a message occurred | |
onError | (evt: MessageEvent) => void | function that will be execute when an error message occurred |
UseBroadcastChannelResult
@templateT Type of the data exchanged on the channel.
Result tuple returned by useBroadcastChannel.
| Index | Type | Description |
|---|---|---|
[0] | T \| undefined | Last received message data. undefined before any message arrives. |
[1] | (data: T) => void | send — broadcasts data to all other contexts subscribed to the same channel name. |
