npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@iampoul/usebroadcast

v1.0.2

Published

A React hook for cross-tab communication and leader election using the Broadcast Channel API.

Readme

Socket Badge

useBroadcast Hook

A React hook for cross-tab communication and leader election using the Broadcast Channel API.

Installation

npm install @iampoul/usebroadcast

Usage

import React, { useEffect } from 'react';
import { useBroadcast } from 'use-broadcast';

function App() {
  const {
    tabId,
    isLeader,
    connectedTabs,
    serverConnected,
    setServerConnected,
    broadcast,
    sendToLeader,
    registerMessageHandler,
  } = useBroadcast({ channelName: 'my-app-channel' });

  useEffect(() => {
    // Example of a custom message handler
    const unregister = registerMessageHandler('my_custom_message', (payload) => {
      console.log(`Received custom message from tab ${payload.senderId}:`, payload.payload);
    });

    // Example of a message handler for messages sent to the leader
    const unregisterLeader = registerMessageHandler('my_leader_message', (payload) => {
      if (isLeader) {
        console.log(`Leader received message:`, payload);
      }
    });

    return () => {
      unregister();
      unregisterLeader();
    };
  }, [registerMessageHandler, isLeader]);

  const handleSendMessage = () => {
    broadcast('my_custom_message', { text: 'Hello from another tab!' });
  };

  const handleSendToLeader = () => {
    sendToLeader('my_leader_message', { task: 'do something important' });
  };

  return (
    <div>
      <h1>useBroadcast Example</h1>
      <p>Tab ID: {tabId}</p>
      <p>Is Leader: {isLeader ? 'Yes' : 'No'}</p>
      <p>Server Connected: {serverConnected ? 'Yes' : 'No'}</p>
      <button onClick={() => setServerConnected(!serverConnected)}>
        Toggle Server Connection
      </button>
      <h2>Connected Tabs:</h2>
      <ul>
        {connectedTabs.map((tab) => (
          <li key={tab.id}>
            {tab.id} {tab.isLeader ? '(Leader)' : ''} - Last Seen: {new Date(tab.lastSeen).toLocaleTimeString()}
          </li>
        ))}
      </ul>
      <button onClick={handleSendMessage}>Send Custom Message to All Tabs</button>
      <button onClick={handleSendToLeader}>Send Message to Leader</button>
    </div>
  );
}

export default App;

Return Values

The useBroadcast hook returns an object with the following properties:

  • tabId: A unique identifier for the current tab.
  • isLeader: A boolean that is true if the current tab is the leader, and false otherwise.
  • connectedTabs: An array of objects, where each object represents a connected tab and has the following properties:
    • id: The unique identifier of the tab.
    • isLeader: A boolean that is true if the tab is the leader, and false otherwise.
    • lastSeen: The timestamp of the last time the tab was seen.
  • serverConnected: A boolean that represents the status of the server connection. This is not managed by the hook, but is provided as a convenience for the user to track the server connection status.
  • setServerConnected: A function that takes a boolean and sets the serverConnected state.
  • broadcast: A function that takes a type and a payload and sends a message to all connected tabs.
  • sendToLeader: A function that takes a type and a payload and sends a message to the leader tab.
  • registerMessageHandler: A function that takes a type and a handler and registers a handler for a specific message type. It returns a function that can be called to unregister the handler.

Author