Update (02.02.2019): more than two years ago, while experimenting with RxJS and React, I’ve created a library presented in this post. Please note that in the meantime, that library was deprecated.
Using observables seems like a good thing. So why don’t we use it in React apps more often?
With observables we can easily manage asynchronous data streams, but what is a stream in a React component?
To determine this, let’s start by analyzing a simple ClickCounter example:
Simple React ClickCounter component
This is a component describing asynchronous behavior. On every click
event on a button
tag, the state is changed. Or in other words, the state changes as a result of events happening over time.
A sequence of ongoing events ordered in time is a definition of a — stream.
So, instead of defining this.state
as an object which will later be overwritten, we can define it more declaratively:
Defining state as a stream
However, even when defined like this, how will our component know when to update? Somebody still has to invoke this.setState()
.
There are some existing solutions for achieving this, but it seemed a bit too complicated to me.
Other more popular options for using “Functional Reactive paradigm” requires you to use another framework or another programming language (like Cycle.js or elm).
But I didn’t like the idea of losing all good things React offers you.
So, I created a small library called Recycle, which is my attempt at solving this issue. It converts “functional/reactive object description” into a React component.
Here is how a ClickCounter looks like when defined using Recycle:
It works by “monkeypatching” React.createElement
. Before a component is rendered, if a select query is matched with node element, recycle sets inline event listener defined inupdate
function.
Each time event handler dispatches an event, it calls selectedNode.rxSubject.next(e)
In short, Recycle creates a classical React component out of this object by creating inline event handlers and handles component local state by using “Redux style” reducer operator.
Classical React component — mixing logic and structure
handleClick
events or this.setState
statements that you need to worry about.state = reducer(state, action)
.forceUpdate
or shouldComponentUpdate
)this.refs
) for external plugins or similarIf posts like this are interesting to you, consider subscribing to my mailing list. Don’t worry, I wont spam you — usually it takes me about two months for a single post :)