Skip to content

useBroadcastChannel

that provides cross-tab/window communication

browser
low
test coverage
Last changed: 8 months ago

TIP

This hook uses BroadcastChannel browser api to provide enhanced functionality. Make sure to check for compatibility with different browsers when using this api

Installation

Library
CLI
Manual
typescript
import { useBroadcastChannel } from '@siberiacancode/reactuse';

Usage

typescript
const { supported, data, post, error } = useBroadcastChannel('channel');

Demo

Api

Parameters

NameTypeDefaultNote
namestring-The name of the channel
callbackFunction-A callback function that will be called when a message is received

Returns

UseBroadcastChannelReturn

Type declaration

typescript
export interface UseBroadcastChannelReturn<Data = unknown> {
  /** The underlying BroadcastChannel instance if supported, undefined otherwise */
  channel?: BroadcastChannel;
  /** Whether the channel has been closed */
  closed: boolean;
  /** The most recently received data from other contexts */
  data?: Data;
  /** Error object if any error occurred during channel operations */
  error?: Event;
  /** Whether the BroadcastChannel API is supported in the current environment */
  supported: boolean;
  /** Function to close the channel and clean up resources */
  close: () => void;
  /** Function to send data to other contexts through the channel */
  post: (data: Data) => void;
}

Source

SourceDemo

Contributors

D
debabin
debabin

Released under the MIT License.