How to Render Streams with React

Learn how to simplify streams rendering with Kefir and React

TLDR; You don’t have to be a javascript ninja to start using streams with React. The article shows a few examples demonstrating how and the component that makes it all so simple.

Photo by Florian Wehde on Unsplash

Streams are awesome. Everything that happens on client-side can be reduced into a stream: a stream of DOM updates, a stream of redux state changes, a stream of scrolling events, etc.

It implies that mastering streams skill is a crucial part of modern client-side engineering.

Luckily, there is a very simple way of how to use/render streams with React. And by rendering a stream I mean converting data from a stream into something visual. It can be a value like a date/time or behavior of elements on a page.

Tip: Use Bit to build better apps with components as a team. Easily reuse components across repos, keep your UI standardized across apps, collaborate over components in different projects and build faster. Try it out.

Few Examples

Let's start with a few examples, if you are short on time, then scroll to the end of the article where I’ll describe how to actually render a stream, it is pretty simple, I promise!

For streams, I’ll be using awesome Kefir library. Highly recommend it, but it is up to you which library you would prefer, it does not really matter.

Date/Time

Let’s render the date/time value that updates every second. If you ever tried that, you might remember how bulky such a simple component might look like, but with a stream, it is very simple:

Scroll

A bit more complicated example would be a component that renders a custom scroll bar.

Again, super simple. Here we have a simple scroll stream that mapped into a scrolled percentage stream, which then used to set top value for scroll bar cursor styles.

Animations

If you ever used a library like react-transition-group, then the code would probably look familiar to you. But the thing I like the most is that we don’t have to load additional dependency for animations, streams library and a little bit code is all we need:

This is a bit longer than previous examples, but still about 20x shorter than the react-transition group lib. Of course, it has fewer features, but there is a lot of room for a few more lines of code.

FromStream component

So, let’s have a look at the FromStream component itself:

Nice and simple 42 lines of code. No magic. But gives a great power to work with streams in React app.