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

react-ebus

v1.0.1

Published

A lightweight and flexible event bus for React, designed to simplify inter-component communication using event-driven architecture.

Readme

react-ebus

A lightweight and flexible event bus for React, designed to simplify inter-component communication using event-driven architecture.

npm
GitHub stars


🚀 Features

✅ Easy to integrate with any React project
✅ TypeScript support out of the box
✅ Supports both global and scoped events
✅ Handles dynamic event registration and cleanup
✅ Clean API for emitting and listening to events
✅ Fully compatible with React 19

📦 Installation

Install the package using npm:

npm install react-ebus

or with yarn:

yarn add react-ebus

🔥 Demo

Open in StackBlitz


🔨 Usage

1. Setup EventProvider

Wrap your app with the EventProvider to initialize the event bus:

import React from "react";
import { EventProvider } from "react-ebus";

const App = () => {
  return (
    <EventProvider
      registerEvents={{
        userlogin: "user:login",
        userlogout: "user:logout",
      }}
      allowAllEvents={false}
    >
      {/* If `allowAllEvents` is false, only registered events will be allowed */}
      <YourComponent />
    </EventProvider>
  );
};

export default App;

2. Emit Events using useEventEmitter

Use the useEventEmitter hook to emit events from any component.

import { useEventEmitter } from "react-ebus";

const YourComponent = () => {
  const { emit, eventList } = useEventEmitter();

  const handleLogin = () => {
    emit("user:login", { id: 1, name: "John Doe" }); // Emit directly by event name
  };

  const handleLoginWithRegisteredEvent = () => {
    emit(eventList.userlogin, { id: 1, name: "John Doe" }); // Emit using registered events to avoid typos
  };

  return (
    <div>
      <button onClick={handleLogin}>Login</button>
      <button onClick={handleLoginWithRegisteredEvent}>
        Login with Registered Event
      </button>
    </div>
  );
};

3. Listen to Events using useEventListener

Use the useEventListener hook to listen for events.

import { useEventListener } from "react-ebus";

const YourComponent = () => {
  const { unregister, unregisterAll } = useEventListener(
    {
      "user:login": (data) => {
        console.log("User logged in:", data);
      },
      "user:logout": () => {
        console.log("User logged out");
      },
    },
    { allowedAllEvents: false }
  );

  return (
    <div>
      <p>Listening for login and logout events...</p>
      <button onClick={() => unregister("user:login")}>
        Unregister Login Event
      </button>
      <button onClick={unregisterAll}>Unregister All Events</button>
    </div>
  );
};

🛠️ Props

EventProvider Props

| Prop | Type | Required | Description | | ------------------ | ----------------------- | -------- | ----------------------------------------------- | | registerEvents | {[key:string]:string} | ❌ | List of allowed event names. | | allowAllEvents | boolean | ❌ | If false, only registered events are allowed. |


useEventEmitter Props

| Prop | Type | Description | | ------------------ | ---------------------------------------------- | --------------------------------------------------- | | emit | (eventName: string, payload?: any) => void | Function to emit an event with an optional payload. | | eventList | {[key: string]: string} | List of registered events. | | isEventAllowed | (eventName: string) => boolean | Function to check if an event is allowed. |


useEventListener Props

| Prop | Type | Required | Description | | ---------------- | --------------------------------- | -------- | ------------------------------------------------------ | | eventListeners | Record<string, EventHandler> | ✅ | Object mapping event names to handler functions. | | configuration | Partial<UseEventListenerConfig> | ❌ | Configuration object for allowing unregistered events. |


EmitConfig Props (Optional)

| Prop | Type | Description | | ------------------ | --------- | -------------------------------------------------- | | allowedAllEvents | boolean | If true, allows emitting events even if unregistered. |


🎯 Example

Combined Example with Emit and Listener:

import React from "react";
import {
  EventProvider,
  useEventEmitter,
  useEventListener,
} from "react-ebus";

const App = () => (
  <EventProvider
    registerEvents={{ customEvent: "custom:event" }}
    allowAllEvents={false}
  >
    <ComponentA />
    <ComponentB />
  </EventProvider>
);

const ComponentA = () => {
  const { emit } = useEventEmitter();

  return (
    <button onClick={() => emit("custom:event", { message: "Hello from A!" })}>
      Emit Event
    </button>
  );
};

const ComponentB = () => {
  useEventListener({
    "custom:event": (data) => {
      console.log("Event received:", data);
    },
  });

  return <div>Listening for events...</div>;
};

📜 TypeScript Support

Types are included out of the box:

export type EventHandler = (...args: any[]) => void;

export interface UseEventListenerConfig {
  allowedAllEvents?: boolean;
}

🚧 Development

Run TypeScript Check:

npm run type-check

Build the Package:

npm run build

Publish to npm:

npm publish --access public

✅ Best Practices

✔️ Always define and register events in EventProvider.
✔️ Clean up event listeners to avoid memory leaks.
✔️ Use TypeScript to ensure type safety.
✔️ Handle unknown or unregistered events gracefully.


⭐ Support the Project

If you like this project, consider giving it a ⭐ on GitHub!

GitHub stars


👨‍💻 Author

Created by Saurabh


📄 License

This project is licensed under the MIT License.


🔥 Changes Made:

✅ Updated with useEventEmitter and useEventListener changes.
✅ Improved formatting for better readability.
✅ Added demo link and GitHub star button.
✅ Fixed consistency across examples.