While working on web or mobile components, It is one of the common requirements to share data between multiple components. There are few common ways by which data is shared between multiple components in ReactJS application.
There is one more way by which data can be shared easily between multiple components in the Reactjs application, Which is using rxjs library.
It is assumed that Rxjs is mainly used with Angular projects, But it is not true. Rxjs is totally separate library that can be used with other JavaScript libraries/Frameworks also like ReactJS and Vue.
This method is used by React components to subscribe to messages that are sent to an observable.
This method is used to send messages to an observable which are then sent to all React components that are subscribers (a.k.a. observers) of that observable.
In the example, We will try to send the data from a child component to parent component and data can be shared with any type of component like parent to child, child to parent or deeply nested components, etc.
Here we will use a message service by which we can subscribe to new messages in any component with the getMessage() method, send messages from any component with the sendMessage(message) method, and also if needed we can clear/delete the data from the variable using clearMessages() method.
Let's see the code inside the file message.service.ts file. It actually does the real work for data communication. We will import Subject from rxjs library and then create methods to set/get/delete the value from the Subject.
In this component, we will mainly set the value of Message which can subscribe to any of the components wherever we need the specific data.
This component uses the message service to subscribes to the data from the Subject, Push them to the variable and then render it in the JSX part. Let's see the code below
Important Note!
While using Subject, When you subscribe to an observable or event in JavaScript, you should always need to unsubscribe at a certain point to release memory in the system. Otherwise, you will have a memory leak.
With the help of Observable, Data can be shared with the components with any relation. And I believe it is one of the quickest ways to share the data between Components.
I hope this article helped you to understand How to communicate between Components with Observable & Subject. You can also find other demos/articles here to start working on enterprise-level applications.
Let me know your thoughts over email pankaj.itdeveloper@gmail.com. I would love to hear them and If you like this article, share it with your friends.
Thanks!