DEV Community

Cover image for How implement Messaging Pattern in React JS without external libraries
Ruben Martinez
Ruben Martinez

Posted on

How implement Messaging Pattern in React JS without external libraries

In React, one of the first big issues that comes up is figuring out how components should communicate with each other. And yes, sometimes you can solve your communication issues with Flux, but no it is NOT necessary. Some developers use Flux just because it's popular - without realizing that simpler solutions exists.

To avoid deep in all the details, the quick answer to implement the Messaging Pattern is using Context. Context works similarly to props, but instead of providing data to a single child, it can be used to provide data to an entire subtree. (Child of a child, child of a child of a child, and so on). Context was designed to send data down the tree (parent to subtree child). But It can be paired with callback functions to pass data back up (subtree to parent).

Now, knowing the key “Context”, let me show you the quick example, to send message to all the components in the project.

First we need create the Context. APPContext.js, and define the message Object and the Send Message action.

Image description

In our Root App we need to add our context provider to share the same context with any component consumer.

Image description

Now, any react component can send a Message using the shared context.

Image description

And the last piece in this pattern is the subscriber. Any component could be a subscriber with just add the context consumer tag, and add the action (Handle Message) with the message received.

Image description

Now, you can have the messaging pattern in your React project without Redux or other libraries. The Next step is create a Custom Hook, to convert this pattern in a service technology... I'll write other article with it.

Top comments (0)