Saturday, October 24, 2020

How to use React Event Emitter 3

Install event emitter using this command

npm install --save eventemitter3  

This is npm page for the package we are going to use.

https://www.npmjs.com/package/eventemitter3 

Let's be patient while this npm package installed. And we are ready to proceed.

It is better if we create this event emitter related code in a one file. It is plain javascript file, emitter.js in my case.

import EventEmitter from 'eventemitter3';
const eventEmitter = new EventEmitter();
const Emitter = {
  on: (event, fn) => eventEmitter.on(event, fn),
  once: (event, fn) => eventEmitter.once(event, fn),
  off: (event, fn) => eventEmitter.off(event, fn),
  emit: (event, payload) => eventEmitter.emit(event, payload),
};
Object.freeze(Emitter);
export default Emitter;


So now we can import this event emitter (emitter.js) to any component like below

import Emitter from '<path-to-event-emitter>/emitter';

 

Now let's assume we need to fire an event based on some condition. We can emit event like in below code.

Emitter.emit(SOME_CONSTANT_EVENT_NAME_ONE, {data_object_for_the_called_function} );

 

And also we need to an event listener for this SOME_CONSTANT_EVENT_NAME_ONE. We can define that event listener in another file or same file, as defined below.

useEffect( () => {
    Emitter.on(SOME_CONSTANT_EVENT_NAME_ONE, someFunction);
    return () => {
      Emitter.off(SOME_CONSTANT_EVENT_NAME_ONE, someFunction);
    };
} )

someFunction = (data) => {
    // do something with data
}

 

That's the very simple example of using React event emitter3. We can emit and catch multiple events using different event names (like SOME_CONSTANT_EVENT_NAME_ONE).

The main advantage taken from the event emitter was communicating changes happened in a component to another component, in projects where Redux is not used. And those communicating components were far way in the component hierarchy.