DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

horhorou
horhorou

Posted on

A native package that you should use on React

Recently, on my company's project I made a surprising discovery when I needed to communicate with a few components that were too far apart + interact with my state manager.
And that's when I made a surprising discovery of a natively existing packageΒ : EventEmitter


It is through a todo app that we will explore the eventΒ emitter

For a simple example we'll take a todo list with a button that deletes all data and a second one that resets the default data.

Inside the Sidebar component, nothing very complex,a container and the two buttons that are linked to two methods: onDelete _and _onReset

These methods are inside the Sidebar component

Now let's get to the heart of the matter, how the EventEmitter works.

Basically, it is a class that we will have to instantiate from the events package.
The principle remains the same as an addEventListener.

Once this is done, we can use it in our code and for that we will focus on three essential methodsΒ :

addListener('nameOfSignal', methodToExecute)
Subscribe to an event
emit('nameOfSignal', args?)
Dispatch an event
removeListener('nameOfSignal', linkedMethod)
Unsubscribe from an event

Our App.js file will listen to the events triggered by our buttons in the sidebar, it will only need the _addListener _and the _removeListener _when the component is removed

On the other hand, our Sidebar.js file contains the methods to trigger the event

So when we click on our delete button, all the components that are listening to the "delete" event will execute their respective methods.

In our case, we have only one component listening to the delete event and its method will allow us to set the state to an empty array

The reset method will allow us to reset the state to the default state, leaving us with the default tasks.

If you want to test quickly what it gives and tweak the code a bit, here is the CodeSandbox


Hopefully you learned something today, feel free to tell me in the comments if you knew the EventEmitter class and in which cases you use it

Until then, take care

Top comments (0)

πŸŒ–πŸŒ—πŸŒ˜ Turn on dark mode in Settings