use-event-bus-hook
v0.0.3
Published
This hook enables the use of the event bus pattern in React with zero external dependencies
Downloads
2
Maintainers
Readme
useEventBusHook
This hook enables the use of the event bus pattern in React with zero external dependencies and ensures automatic event listener removal during cleanup, preventing memory leaks.
How to use it:
- First, install the package.
npm install use-event-bus-hook
OR
yarn add use-event-bus-hook
- Add the following code into the component from which you intend to emit the event.
import { EventBus } from "use-event-bus-hook";
const onClick = () => {
EventBus.emit("EVENT_NAME", 5);
}
- Add the following code into the component where you intend to listen for the event.
import { useEventBus } from "use-event-bus-hook";
const handler = (e) => console.log(e.details); // 5
useEventBus("EVENT_NAME", handler);
Note: Ensures that the event name should be same in both the components.
Options:
- eventBus
| Property | Description | Type
| :------------------ |:----------------------------------:| :---------------------
| on | Listen to event | function(event: string, callback) | |
| once | Listen to event only once | function(event: string, callback) |
| emit | Send the data | function(event: string, data) |
| off | Remove the listener | function(event: string, callback) |
- useEventBus
| Property | Description | Type
| :------------------ |:----------------------------------:| :---------------------:|
| name | unique event name | string | |
| handler | Trigger when event is captured | function(event) |
License
MIT © pulkitchdha