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 wasdeprecated.
Using observables seems likea good thing. So why don’t we use it inReact 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 simpleClickCounter example:
This is a component describing asynchronous behavior. On everyclick
event on abutton
tag, the state is changed. Or in other words, the statechanges as a result ofevents happeningover time.
A sequence of ongoing events ordered in time is a definition of a —stream.
So, instead of definingthis.state
as an object which will later be overwritten, we can define it more declaratively:
However, even when defined like this, how will our component know when to update? Somebody still has to invokethis.setState()
.
There are someexisting 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 anotherprogramming language (likeCycle.js orelm).
But I didn’t like the idea of losing all good things React offers you.
So, I created a small library calledRecycle, which is my attempt at solving this issue. It converts “functional/reactive object description” into a React component.
Here is how aClickCounter 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 callsselectedNode.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.
handleClick
events orthis.setState
statements that you need to worry about.state = reducer(state, action)
.forceUpdate
orshouldComponentUpdate
)this.refs
) for external plugins or similarIf posts like this are interesting to you, consider subscribing to mymailing list. Don’t worry, I wont spam you — usually it takes me about two months for a single post :)