Should I learn RxJS?

Should I learn RxJS?

Updated:
Published:

Do you ask yourself whether it's worth the effort learning RxJS? It's time to collect some facts you should take into consideration before you make your choice. In this article, we will talk about what problems RxJS tries to solve and what the tradeoffs of using this library are. After reading this, you should be well-equipped for a good decision.

Cover image

Which problems does RxJS solve for us?

Let’s have a quick glance at their Homepage:

REACTIVE EXTENSIONS LIBRARY FOR JAVASCRIPT

RxJS is a library for reactive programming using Observables, to make it easier to compose asynchronous or callback-based code. […]

https://rxjs.dev

So, here we have the answer: RxJS claims to simplify the composition of asynchronous or callback-based code .

And it does so by providing an implementation of the Observer pattern to enable us to write reactive code … interesting!

What exactly this means is a topic for another blog post. It will be linked here. If you want to stay tuned on this, consider following us on twitter .

What are the characteristics of RxJS?

When deciding whether it makes sense to use a library, we should also take a look at some characteristics of the library itself.

What does code written with RxJS look like?

Now let’s see what it actually looks like, if we write some code in RxJS.

A nice use case is an autocomplete search for books.

const url = `https://gutendex.com/books`;

export const autocomplete = (input) => {
  // on every input event
  return fromEvent(input, "input").pipe(
    // wait until pause of 200ms
    debounceTime(200),
    // get input the value
    map(() => input.value),
    // swallow unchanged values
    distinctUntilChanged(),
    // send the request and if
    // a previous one is ongoing,
    // cancel it beforehand
    switchMap((search) => {
      const params = new URLSearchParams({ search });
      return fromFetch(`${url}?${params}`);
    }),
    // parse json body (async)
    switchMap((res) => res.json()),
    map((obj) => obj.results as Result[]),
  );
};

You can then bind this search to an input like this:

const input = document.querySelector("input");
const items = document.querySelector("ul");

autocomplete(input).subscribe((results) => {
  const renderedItems =
    results.length === 0
      ? ["<li>No results 👻 try again</li>"]
      : results.map(({ title, authors: [author] }) => {
          const name = author?.name ?? "[unknown]";
          return `
              <li>
                <b>${title}</b> - ${name}
              </li>
            `;
        });
  items.innerHTML = renderedItems.join("");
});

See it in action

I would say, this is straight-forward. Now imagine that we wanted to implement this in vanilla JS. It would be challenging to create such a concise way of expressing the behavior above.

RxJS has plenty of operators that you can use to control the stream of events flowing through our observable chains.

Are there any drawbacks?

Now that we had a glance at what RxJS can do for us, it’s time to see what the potential drawbacks are.

Bundle size

Naturally, every library that you add, increases the bundle size. The 18 KB listed above are the total bundle size. RxJS is modular and treeshakble, but still, you would want to decide from case to case whether it’s worth this extra payload.

Learning curve

RxJS is quite hard to master. Mainly this is because of the operators (and other stuff like Subjects and caching). I did not use every one of them yet, and I never will.

But it helps a lot, if you have a good clue about a large set of those operators, to really be productive using RxJS.

Easy to be overused

RxJS is not a silver bullet, and not everything turns into a nail if you grab a hammer.

It was built to tackle asynchronous problems. Hence, you should not misuse it to manipulate arrays, for example. There are libraries that are more suitable for this, like lodash .

But even if you are writing asynchronous code, often using a simple promise can be totally sufficient.

Keep in mind that you cannot use something like async/await for Observables. In some other languages like Dart, you have streams baked into the language itself, which makes reactive code easier to read and understand.

Long stack traces

While quite performant, there is a lot of stuff going on in RxJS. And asynchronous call stacks are not everyone’s favorite. This can easily lead to confusion, and it’s sometimes a good idea to blacklist RxJS internal logs.

Is it worth learning?

So, let’s come back to the starting question.

The answer is — as almost always — a clear “It depends …” .

Here are some considerations you should make, if you are to decide whether you want to introduce RxJS into our codebase.

Are you building an app or a mostly static website?

If you are building an app, you may have a lot of complex stuff going on. It is likely that you can profit from RxJS in some situations. Angular, for example, already ships with RxJS and builds on it. RxJS is also well-fit for state management and can be very useful to publish your state through your app.

If you are creating a customer-facing mostly static website that has to load blazing fast, you should be fighting against every little KB of code. You seldom will have complex asynchronous problems on such a site anyway.

Do you and your team have the time to learn it?

Let’s face it. You want to avoid overwhelming a total beginner, nor is every developer as awesome as you are and does not want to take the extra mile expanding his or her tool set. So think about whether your team is capable and willing to learn this new library before you just npm install it.

Final words

As awesome developers, we are always eager to learn something new.

Learning RxJS in depth was not my main focus when I started off with Angular 2 back in 2016. Since then, I regularly solved problems with this library and became confident in using it. Currently, I use it mainly in NodeJS and for state management in web apps.

RxJS definitely influenced the way I think about some categories of software problems, and I don’t regret having learned it.

So, I can certainly tell that it was worth the effort learning RxJS for me.