In this article, we will analyze two use cases: one in a pure JavaScript environment and the other integrated into a React application, to demonstrate how RxJS optimizes event and state management, significantly improving application efficiency and reactivity.
Why use RxJS today
Efficiency and reactivity: offers an Observable-based programming model that allows managing data flows and events more efficiently and reactively. This is particularly useful in web applications where asynchronous management and reactivity are critical, such as in Single Page Applications (SPA) or real-time applications
Scalability and maintainability: code tends to be more scalable and easy to maintain. Observables help manage complex states and event sequences in a more predictable and less error-prone way compared to traditional callbacks or promises
Composition and code reuse: promotes declarative programming, where it's possible to create highly composable and reusable data flows. This reduces boilerplate and improves code modularity
Plain JavaScript
Create a folder for your project and navigate inside
mkdir rxjs-example
cd rxjs-exampleInitialize a new Node.js project
npm init -y
npm install rxjsSuppose we want to create a data flow that reacts to clicks on a button
<button id="myButton">Cliccami</button>import { fromEvent } from 'rxjs';
import { scan } from 'rxjs/operators';
const button = document.getElementById('myButton');
const clicks$ = fromEvent(button, 'click');
const subscription = clicks$.pipe(
scan(count => count + 1, 0)
).subscribe(count => console.log(`Cliccato: ${count} volte`));
// Ricorda di disiscriverti quando non serve più
// subscription.unsubscribe();
Using fromEvent, we generate an Observable that reacts to button click events
The scan operator is then applied to accumulate an incremental count every time the button is clicked, starting from zero. This count is displayed in the console every time a click occurs
It's important to remember to unsubscribe from the Observable with unsubscribe() when no longer needed, to avoid memory leaks, especially in applications with many components or that need resource cleanup
RxJS with ReactJs
Create a new React project using Create React App
npx create-react-app react-rxjs-example
cd react-rxjs-exampleInstalling RxJS
npm install rxjs// click-counter.component.js
import React, { useEffect } from 'react';
import { fromEvent } from 'rxjs';
import { scan } from 'rxjs/operators';
const ClickCounter = () => {
useEffect(() => {
const button = document.getElementById('myButton');
const clicks$ = fromEvent(button, 'click');
const subscription = clicks$.pipe(
scan(count => count + 1, 0)
).subscribe(count => console.log(`Cliccato: ${count} volte`));
return () => {
subscription.unsubscribe();
};
}, []);
return <button id="myButton">Cliccami</button>;
};
export default ClickCounter;Make sure to include the ClickCounter component in App.js or another container component.
import React from 'react';
import ClickCounter from './click-counter.component';
export const App = () => {
return (
<div className="App">
<ClickCounter />
</div>
);
}
export default App;RxJS emerges as a powerful and versatile solution for managing events and asynchronous data in modern applications. Adopting this library can significantly transform the approach to reactive programming, both in pure JavaScript contexts and those based on frameworks like React!
Thanks to Observables and RxJS operators, developers can build cleaner, more maintainable and performant applications, managing complex data flows with greater elegance and less boilerplate code
And you? Do you use RxJS or know any alternatives?
