🚀 DAY 5 OF LAUNCH WEEK:Introducing Webhook Events for Alert Changes.Learn more
Socket
Book a DemoInstallSign in
Socket

@saurabhcoded/react-eventbus

Package Overview
Dependencies
Maintainers
0
Versions
7
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install
Package was removed
Sorry, it seems this package was removed from the registry

@saurabhcoded/react-eventbus

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

unpublished
latest
Source
npmnpm
Version
1.0.6
Version published
Maintainers
0
Created
Source

@saurabhcoded/react-eventbus

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 @saurabhcoded/react-eventbus

or with yarn:

yarn add @saurabhcoded/react-eventbus

🔥 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 "@saurabhcoded/react-eventbus";

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 "@saurabhcoded/react-eventbus";

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 "@saurabhcoded/react-eventbus";

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

PropTypeRequiredDescription
registerEvents{[key:string]:string}List of allowed event names.
allowAllEventsbooleanIf false, only registered events are allowed.

useEventEmitter Props

PropTypeDescription
emit(eventName: string, payload?: any) => voidFunction to emit an event with an optional payload.
eventList{[key: string]: string}List of registered events.
isEventAllowed(eventName: string) => booleanFunction to check if an event is allowed.

useEventListener Props

PropTypeRequiredDescription
eventListenersRecord<string, EventHandler>Object mapping event names to handler functions.
configurationPartial<UseEventListenerConfig>Configuration object for allowing unregistered events.

EmitConfig Props (Optional)

PropTypeDescription
allowedAllEventsbooleanIf true, allows emitting events even if unregistered.

🎯 Example

Combined Example with Emit and Listener:

import React from "react";
import {
  EventProvider,
  useEventEmitter,
  useEventListener,
} from "@saurabhcoded/react-eventbus";

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.

Keywords

react

FAQs

Package last updated on 18 Mar 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts