Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to use observables in ReactJS

Understanding Observables

Observables are a design pattern that can be used to manage asynchronous data in a more predictable manner. You can think of them as a way of subscribing to a stream of data. They're a bit like a radio station. With a radio, you tune into a station and then receive a steady stream of music or news. Observables work in a similar way. You subscribe to an observable and then receive a steady stream of data that you can process as it arrives.

In technical terms, an observable is an object that emits events or values over time. These values could be anything: clicks, form inputs, data from a server, etc.

Why Use Observables in ReactJS?

ReactJS is a powerful library for building user interfaces. However, managing state and dealing with asynchronous data can sometimes be a challenge. That's where observables come in. Observables can help to manage complex state changes and asynchronous events in a more predictable way.

Getting Started with Observables

To use observables in ReactJS, you'll need to install the rxjs package. This package provides a set of tools for creating and working with observables.

npm install rxjs

Once you've installed rxjs, you can import the Observable class and start using it in your code.

import { Observable } from 'rxjs';

Creating an Observable

Creating an observable is straightforward. You simply call the Observable.create method and pass in a subscribe function. This function is called whenever someone subscribes to the observable.

Here's an example:

const observable = Observable.create(observer => {
  observer.next('Hello, World!');
});

In this example, the observable emits a single value, "Hello, World!". The observer.next method is used to emit a value from the observable.

You can emit as many values as you like, and they don't have to be the same type. For example:

const observable = Observable.create(observer => {
  observer.next('Hello, World!');
  observer.next(42);
  observer.next({ name: 'Alice' });
});

Subscribing to an Observable

Subscribing to an observable is just as straightforward. You call the subscribe method on the observable and pass in an observer object.

Here's an example:

observable.subscribe({
  next: value => console.log(value),
});

In this example, the observer object has a single method, next, which is called whenever the observable emits a value. In this case, it simply logs the value to the console.

Unsubscribing from an Observable

To stop receiving values from an observable, you can unsubscribe from it. When you call subscribe, it returns a subscription object. You can call the unsubscribe method on this object to stop receiving values.

Here's an example:

const subscription = observable.subscribe({
  next: value => console.log(value),
});

subscription.unsubscribe();

In this example, we store the subscription object in a variable, then call unsubscribe on it. After this, the observer will no longer receive values from the observable.

Using Observables in ReactJS

So how do you use observables in a ReactJS component? One way is to subscribe to the observable in the componentDidMount lifecycle method, and unsubscribe in the componentWillUnmount method.

Here's an example:

import React from 'react';
import { Observable } from 'rxjs';

class MyComponent extends React.Component {
  componentDidMount() {
    this.observable = Observable.create(observer => {
      observer.next('Hello, World!');
    });

    this.subscription = this.observable.subscribe({
      next: value => console.log(value),
    });
  }

  componentWillUnmount() {
    this.subscription.unsubscribe();
  }

  render() {
    return <div>My Component</div>
  }
}

In this example, we create an observable and subscribe to it in the componentDidMount method. We then unsubscribe from it in the componentWillUnmount method.

Conclusion

Imagine you're a space explorer, and observables are your friendly alien buddies who keep you updated about different events happening around the universe. They inform you about every single event until you tell them to stop. That's what observables are in the world of programming.

Using observables in ReactJS isn't something you'll always need to do, but they can be a powerful tool when dealing with complex state or asynchronous data. They provide a predictable way to handle data over time, and can help to simplify your code and make it easier to reason about.

So the next time you're working with ReactJS and find yourself wrestling with state or asynchronous data, remember your friends, the observables. They're always there to help, beaming data your way, one piece at a time.