https://github.com/mg-kh/event-bus-react
This hook can carry events across the app.
https://github.com/mg-kh/event-bus-react
event publish-subscribe react-hooks
Last synced: 23 days ago
JSON representation
This hook can carry events across the app.
- Host: GitHub
- URL: https://github.com/mg-kh/event-bus-react
- Owner: mg-kh
- License: mit
- Created: 2023-03-27T10:22:35.000Z (over 2 years ago)
- Default Branch: main
- Last Pushed: 2023-04-03T07:15:39.000Z (over 2 years ago)
- Last Synced: 2025-08-09T05:50:29.421Z (2 months ago)
- Topics: event, publish-subscribe, react-hooks
- Language: JavaScript
- Homepage: https://www.npmjs.com/package/event-bus-react
- Size: 68.4 KB
- Stars: 6
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: readme.MD
- License: LICENSE.txt
Awesome Lists containing this project
README
# React Event Bus
## Old Usages ( < v 1.0.0 )
```javascript
import useEventBus from "event-bus-react";const App = () => {
const { subscribe } = useEventBus("MyEvent"); // default EventBussubscribe("alert", (data) => {
console.log(data);
});const handleEmitEvent = () => {
MyEvent.emit("alert", { sayHello: "hello" });
};return (
<>
Emit Event
>
);
};
```---
## New Usages ( >= v1.0.0 )
1.) Install event-bus-react package from npm.js
```javascript
npm i event-bus-react
```2.) Declare useEventBus() in the entry file of react or next.js project.
```javascript
import useEventBus from "event-bus-react";useEventBus();
```3.) Subscribe the event anywhere in the component or pages.
```javascript
import { subscribe } from "event-bus-react";subscribe(
"show-alert",
() => {
// do something...
},
[]
);
```4.) Emit the event wherever you are in the component tree.
```javascript
EventBus.emit("show-alert");
```---
## Api Declaration
### useEventBus(name)
```javascript
useEventBus(); // EventBus
useEventBus("MyCustomEvent");
```## subscribe(eventName, callBack, dependencies)
```javascript
subscribe("show-alert", (data) => {
alert(data?.message);
});subscribe(
"show-result",
() => {
console.log(a + b);
},
[a, b]
);
```## emit(eventName, data)
```javascript
EventBus.emit("show-alert", { message: "hello" });MyCustomEvent.emit("show-result");
```