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 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-broadcast-channels

v0.0.3

Published

**A React hook for using BroadcastChannel API for seamless communication between components.**

Downloads

13

Readme

react-broadcast-channels

A React hook for using BroadcastChannel API for seamless communication between components.

Installation:

npm install react-broadcast-channels

or

yarn add react-broadcast-channels

Usage:

1. Global Application Behavior (App.js):

This example demonstrates using react-broadcast-channels in your root App.js file to manage global application state updates on login and logout events.

import React from 'react';
import { useBroadCast } from 'react-broadcast-channels';

const App = () => {

  const [currentUser, setCurrentUser] = useState(null);
  const logoutCallback = () => {
    logout(); // Implement your logout logic here
    document.title = "App Name";
  };

  const loginCallback = (event) => {
    document.title = "App Name";
    setCurrentUser(event.data.data); // Update user state
    navigate(url); // Navigate to dashboard
  };

  useBroadCast(logoutCallback, loginCallback);

  // ... the rest of your App component
};

export default App;

2. Modular Approach (Dedicated Context):

For more complex applications, consider creating a dedicated Context Provider to encapsulate useBroadCast usage and related functions for specific sections like authentication.

import React from 'react';
import { createContext, useContext, useState } from 'react';
import { useBroadCast } from 'react-broadcast-channels';

const AuthContext = createContext();

const AuthProvider = ({ children }) => {
  const [currentUser, setCurrentUser] = useState(null);

  const logoutCallback = () => {
    logout(); // Implement your logout logic here
    document.title = "App Name";
  };

  const loginCallback = (event) => {
    document.title = "App Name";
    setCurrentUser(event.data.data);
  };

  const { loginChannel, logoutChannel } = useBroadCast(logoutCallback, loginCallback);

  return (
    <AuthContext.Provider value={{ currentUser, loginChannel, logoutChannel }}>
      {children}
    </AuthContext.Provider>
  );
};

// In other components:
const MyComponent = () => {
  const { currentUser, loginChannel, logoutChannel } = useContext(AuthContext);

  // ... use loginChannel and logoutChannel for login/logout functionality
};

export default AuthProvider;

3. Login Component Integration (login.jsx):

import React, { useState } from 'react';
import { useBroadCast } from 'react-broadcast-channels';

const Login = () => {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');

  const { loginChannel } = useBroadCast();

  const handleLogin = async () => {
    // Implement your login logic here, e.g., send a request to your backend
    const response = await fetch('/api/login', {
      method: 'POST',
      body: JSON.stringify({ username, password }),
    });

    if (response.ok) {
      const loginData = await response.json();
      loginChannel.postMessage({
        type: 'login',
        data: loginData,
      });
    } else {
      // Handle login errors
    }
  };

  return (
    <form onSubmit={handleLogin}>
      {/* ... login form fields ... */}
      <button type="submit">Login</button>
    </form>
  );
};

export default Login;

4. Logout Component Integration (logout.jsx):

import React, { useEffect } from 'react';
import { useBroadCast } from 'react-broadcast-channels';

function Logout() {
  const { logoutChannel } = useBroadCast();

  useEffect(() => {
    logout(); // Implement your logout logic here
    logoutChannel.postMessage({ type: "logout" });
  }, [logoutChannel]);

  return <Outlet />; // Assuming you're using a routing library for navigation
}

export default Logout;

Features:

  • Simple and intuitive API, mirroring the Browser BroadcastChannel API.
  • Decouples component communication, increasing maintainability and reusability.
  • Lightweight and efficient, utilizing native browser support.
  • Compatible with multiple tabs and windows, ideal for real-time applications.

Benefits:

  • Centralized Communication: Manage state updates and event handling across various components seamlessly.
  • Improved Modularity: Separate concerns and promote code organization through clear communication channels.
  • Enhanced Reactivity: Enable components to react dynamically to events broadcasted across the application.
  • Efficient State Management: Reduce complexity and optimize state updates.

Limitations:

  • Requires browser support for the BroadcastChannel API (available in most modern browsers).
  • Messages are limited to primitive data types or JSON-serializable objects.
  • Security considerations: ensure messages are properly validated and sanitized to prevent vulnerabilities.

License:

MIT

Contributions:

Welcome! Fork the project and submit pull requests to contribute to its growth and improvement.

Get started today and elevate your React applications with efficient and centralized communication using react-broadcast-channels!