Containers Are Dead. Long Live Observable Combinators

Matti Lankinen
Nov 8, 2015 · 8 min read
Image for post
Image for post

On Wednesday I watched Reactive2015 conference and André Staltz’s talk about Cycle.js and its advantages compared to React. The presentation was awesome but it was a bit misleading — you can do truly reactive programming also with React by combining it with observables. It may not be so “declarative” or “functional” as it is in Cycle but it works and it’s a really powerful way of creating UIs.

I really like Cycle.js. It is simple and declarative. But it has two caveats. First it has hard RxJs dependency and that is too much: if I select a rendering library then I don’t want it to constrain my state handling! Second, Cycle’s DOM event subscription system is not practical (regardless how functional and “reactive” it may be): the emitted data must be encoded into DOM (e.g. by using data attributes like data-id=”myId”). Just ugly.

Single source of Truth. And its problems

The state of your whole application is stored in an object tree inside a single store.

That is a direct quote from Redux website. The most of the current Flux libraries use combined reducer and this has locked the developers’ mindsets to the fact that the state should be like a mega sized “blob” which is passed to the “dummy” components via props. And there is always an explicit layer which separates the state handling and the UI: the top level “application container”. Perhaps you’ve seen this kind of lines in Redux apps:

This single source of truth is a good thing! But the unfortunate truth is that it’s not how React is designed to work. React’s Virtual DOM algorithm and its performance relies heavily on components. Every time the state changes in “megablob” applications, it triggers the virtual DOM rebuild for the entire application! And that is slow, especially if you have a list with size of 100+. You are also forced to continuously pass down the props which causes friction and slows down the development: every time when new feature is added, you must add those props to your elements like

Ever had some frustration when doing this kind of stuff? I’ve had. o/

State with Observables

Image for post
Image for post
Image by Mike Lindsey (CC BY-NC-ND 2.0)

In this section I’ll expect that you have some basic knowledge about observables and Functional Reactive Programming. If you are not familiar with FRP, I strongly advice you to read this one or watch the Staltz’s Reactive2015 presentation.

Now that you are familiar with the basic concepts of FRP, we can start defining our single source of Truth. In these examples I’m using Bacon.js but the same concepts apply to other reactive libraries like Kefir and RxJs as well.

Let’s start. I’m about 80kg and 180cm and that’s the truth which can be described by the means of observables:

Now that we have a weight and height, we can derive the BMI:

And the coolest part of observables is that every time when either weight or height changes, also the BMI changes. But weight and height are constants so they can’t be changed, right? True. So let’s make actions which can modify them. I’m using createAction from MEGABLOB library. It creates a function which can be called like any other functions. In addition, the arguments from function calls are accessible as an observable via .$ property:

And finally we can create the complete state model (Yes! the state model is just a plain object that contains a set of “action creators” and observables):

And the application UI looks like this:

Looks correct, right? But something is wrong. If we run the application we’ll get the following message to our debug console.

Image for post
Image for post

The Truth about Observables and JSX

Image for post
Image for post

The error message pretty much nails it: “Objects are not valid as a React child: Bacon…”. Because weight, height and bmi are Observables, React can’t render them properly.

So there must be a way to “extract” the values from observables. And there is: observable combinators. In Bacon there are combineWith (that was used before), combineAsArray and combineTemplate. In Kefir, there is combine and in RxJs there is combineLatest.

Because we are familiar with combineWith, let’s start with that one:

And now because our App function returns an Observable<JSX>, we can’t render it but we can subscribe into it and render the emitted values (application JSX):

Works like a charm! But there is still way to much repetition with Bacon.combineWith. Lets simplify it. And the key to this solution requires that you understand what is JSX.

Many people think JSX is an unicorn that breaths fire and such things. Nope. Not at all. JSX is just some fancy syntax sugar for a nested graph of plain JavaScript objects.

If it’s an object, we can traverse it — Arnold Schwarzenegger

Well said, Arnold. That is exactly what combineTemplate does. It “lifts” the observables from the nested object graph (JSX) and returns a new combined observable where original observables are replaced with their actual values:

Much better. But the App still returns an observable so it cannot be used as element. Fortunately we have good implementations for Bacon and RxJs how to create a reactive React component. By using those it’s trivial to create the basic reactive application building block — observable combinator component:

Now this Combinator component works like any other “normal” React component, except it accepts Virtual DOM containing Observables. Let’s re-write the application UI by using observable combinators.

Almost like “normal” React application but note that all components are pure. And if you take a look at the renderSlider method, you can see that it is completely unaware whether the given value is observable or not.

And the coolest thing is that even though the state models are nested, they still can be treated as individuals when building your application. In other words, making states containing N arbitrary sub-states (like lists) become fairly trivial:

Image for post
Image for post

Embedding observables to virtual DOM is not a new idea. For example Reagent and Yolk have done this for ages. The main goal of this article is just to show that same things can be done also with React and ES6.

More examples can be found from react-combinators Github project.

How about performance?

Image for post
Image for post

Are Combinators fast? Yes, they are. Especially if there are only small changes in the state at time, they outperform today’s popular megablob-architecture-flux implementations easily.

The reason for the great performance is that combinators leverage (internally) the React’s component based approach and its optimizations. <Combinator> elements act like “guards” to the JSX they surround: if the identity of component’s child element is not changed, then there is no need for virtual DOM diffing. If the child element has changed, then it’ll be re-rendered. This leads to the situation where combinators subscribe only to the observables that are embedded directly under their subtrees. If sub-tree contains another <Combinator> element, observables inside that element belongs to it. This nested structure ensures that only element (sub)trees containing changed observables get updated.

This nested <Combinator> structure and high performance FRP library like Kefir, enables the fast state handling of huge state trees containing e.g. long lists. And no more shouldComponentUpdate hacks. Never again.

However, combinators are not a silver bullet. The small state changes are blazing fast but in contrast, the initial loading time is a bit longer due to observable subscriptions and extra virtual DOM traversal. I hope that this will get fixed in future.

If you’re interested in reactive programming but want to stick with React, observable combinators may be the thing you’re looking for. Currently supported libraries are Kefir, Bacon.js and RxJs. Or if you’re not afraid of losing the React’s rich ecosystem and community, take a look at Cycle.js or Yolk.

Follow Matti Lankinen on Twitter

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store