Skip to content

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

  • @template T Type of the data exchanged on the channel.

Props accepted by useBroadcastChannel.

PropertyTypeRequiredDescription
namestringbroadcast channel name
onMessage(evt: MessageEvent<T>) => voidfunction that will be execute when a message occurred
onError(evt: MessageEvent) => voidfunction that will be execute when an error message occurred

UseBroadcastChannelResult

  • @template T Type of the data exchanged on the channel.

Result tuple returned by useBroadcastChannel.

IndexTypeDescription
[0]T \| undefinedLast received message data. undefined before any message arrives.
[1](data: T) => voidsend — broadcasts data to all other contexts subscribed to the same channel name.

Released under the MIT License.