React Components communication with Custom Events

There are some points in life, where you encounter a case so unique, so different, so unexpected — that the solution just has to be special.
Sep 17, 2019

Intro

We use an everything-is-a-module approach, alongside micro-services everywhere in our company. This usually is a good place to be in. Yet sometimes you reach to a point where you component being a module is just too much.

Case

Imagine the following scenario:

In your website, you have some live tweet viewers. The tweet viewer auto updates, and has a specific server for data fetching. The server API endpoint returns all tweets together. Each tweet viewer is a standalone module, imported from and installed react library you hold.

Cool.

Now, you want to use multiple tweet viewers on screen, while keep calling just one fetch for all of them.

How can we do that?

  • How can we call an inner function of one component, and update all others from it?
  • How can multiple components communicate each other, without using the parent?

Enters CustomEvent

After all, events were invented for a reason. It helps us communicating between different aspects of the web application. User interaction events help us connect UI to logic and create behavior. So why don't we use this mechanism to connect our multiple UI components to data, to create one-way data binding?

Recipe:

  • react tweet viewer components
  • data event router
  • custom event handler
  • async data fetcher

React tweet viewer component

Loading...

App Component

Loading...

Event Handler!

Loading...

Full App

Edit serene-morning-n2rd6