Sharing data between React components using RxJS

In this post, we’ll dive into the wonderful world of RxJS

Chidume Nnamdi 🔥💻🎵🎮
Bits and Pieces

--

The advent of RxJS opened many possibilities in the world of JS. Its goal is to achieve so many with little code. In this post, we will learn how to share data between components in a React app, utilizing the power of RxJS.

Tip: Use Bit to organize and share React components. Share components your team can use and develop in all your apps and build faster together. Try it out.

React Components Collection

Redux

Sharing data among unrelated React components has been the main target of state management libraries. There are many state management implementation but the two most popular are:

  • Flux
  • Redux

Redux was widely adopted because of its simplicity and its use of pure functions. Thanks to its purity, we can be sure that all our reducer functions do not cause side-effects

With Redux, we create a central data store —

then, we connect the components to the datastore and update and delete the state at will. Any changes made to the store will be reflected in all the components connected to the store; this way, data can flow to components, no matter how deeply nested they are. A component in the nth-level in the tree can pass data to the topmost component and the topmost component can pass data to the 21-level component.

RxJS

With RxJS, all the stress and confusion of using state management libraries end. We enjoy the Observer pattern that RxJS brings us.

We simply create an Observable stream and let all components listen on the stream if any component adds to the stream the listening or subscribing components responds to update their DOM.

Setting up

Create a React app using create-react-app. If you don't have create-react-app first, install it globally:

npm i create-react-app -g

Then, scaffold the React project:

create-react-app react-prj

Move into the directory:

cd react-prj

We install the rxjs library:

npm i rxjs

We are going to have a file that instantiates a new BehaviorSubject.

Why use BehaviorSubject? BehaviorSubject is a type of Subject in RxJS, as a Subject child it allows multiple observers to listen on stream and events multicasted to the observers, BehaviorSubject stores the latest value and broadcasts it to any new subscribers.

  • Allows multicasting
  • Stores and multicasts the latest value emitted by subscribers.

We have the messageService.js file located in the src folder. It exports subscriber the instance of BehaviorSubject and the messageService object. The subscriber object is created at the start of the file, so as to be available to any importing component. The messageService object has a send function, which takes a msg parameter which holds the data we need to broadcast all listening components, in the function body we call the emit method in the subscriber object it multicasts the data to the subscribing components.

Let’s say we have components:

  • ConsumerA
  • ConsumerB
  • ProducerA
  • ProducerB

With tree hierarchy:

App component renders ProducerA and ConsumerB, ProducerA renders ConsumerA and ConsumerB renders ProducerB.

The ConsumerA and ConsumerB components keep a state counter individual. In their componentDidMount they subscribe to the same stream subscriber, anytime an event is published they both update the counter. The ProducerA and ProducerB have buttons Increment Counter and Decrement Counter when clicked they emit 1 or -1. The subscribing components ConsumerA and ConsumerB pick up the event and run their callbacks functions thereby updating the value of their state counter and the DOM.

Looking again at the component tree:

The ProducerB was able to comm data to ConsumerA, yet there were not in any way related, and ProducerA was able to pass data to ConsumerB despite not being its parent. That’s the power of RxJS, we merely created a central hub of event stream and let the components listen on it, wherever any component emits events they are picked up by the listening components.

You can play with the app on stackblitz: https://react-lwzp6e.stackblitz.io

Conclusion

In this post, we saw how we can share data between React components using RxJS. We used the BehaviorSubject observable to create a central stream and let other components subscribe to it. These components will get the data when emitted by any component no matter the level of its hierarchy in the component tree.

If you have any questions regarding this or anything I should add, correct or remove, feel free to comment, email or DM me.

Thanks !!!

Learn More

Credits

--

--

JS | Blockchain dev | Author of “Understanding JavaScript” and “Array Methods in JavaScript” - https://app.gumroad.com/chidumennamdi 📕