I always want to make my blog posts more entertaining. Should I be more funny? Should I be clever? Should I be cool? I’m not cool. I’m just going to keep this post short and to the point.
What is a predictable state container?
Predictable state containers are made up of two things: an observable and a reducer. The observable is the container itself and the reducer manages state. State changes within the observable are predictable because all state transformations are made by applying the old state and an action to a pure function (i.e the reducer).
Here’s an example of a predictable state container, in just a few lines of code.
There’s always more than one solution to a given problem. What if redux didn’t exist? How would you build an observable state container?
I’m not going to go into the details of defining reactive programming in this blog post, instead I want to borrow the core principles of Redux (a single source of truth, read-only state and changes made with pure function), and look for different ways to build predictable state containers.
Let’s go back to what a state container is made up of (an observable and a reducer) and approach the problem from two extremes, using some popular libraries.
Building a state container using RxJs
RxJs is everything you could possible want out of observables. It’s set of libraries for composing observable sequences (sometimes referred to as “data streams”). The source of the data stream is event based. It could be: a click event, an ajax requests, an update to a data store, etc.
Let’s take a look at how we would build a predictable state container using RxJs. In the example below we’re building a counter.
Building a state container using Ramda
Ramda is everything you could want out of functional programming. Functions in Ramda are automatically curried and it has an emphasises on a purer functional style of programming.
I think it would be interesting to use transducers to build abstract actions for our data store.
A transducer is function that accepts a reducer and returns a reducer (i.e a pure function).