What the Flux?! Let’s Redux. by Henrik Joreteg

In notebook:
Article Notes
Created at:
2016-02-03
Updated:
2016-02-03
Tags:
JavaScript libraries React jQuery
What the Flux?! Let’s Redux.Henrik argues that the Redux pattern will bring a lot of efficiency and simplification in native web app development. He compares its effect on web development to jQuery, Backbone, Socket.io and React.

The revolution: complete simplification of application state through the virtual DOM

You cannot just put application state into the DOM and read it back from there. It will soon become a huge mess. One solution was the MVC pattern. Except that when you can very inexpensively re-render at will, you don't really need the Model and Collection (and all the baggage such as events, messaging). 
With the MVC implementations we dramatically increase the API surface of the code, that a new developer has to learn. Plus a lot more things that can go wrong.

Plus the question of performance. These implementations (frameworks) need to be downloaded which might be unacceptable on mobile. Second the deep comparisons of properties of the models is quite expensive compared to simple equity comparisons, e.g. ​object1 === object2​.

Instead we could think in immutability. The concept is "If you change it, you replace it". 

He gives these examples of modifying vs replacing:
  // ----
// INSTEAD of this:
var obj = {
    something: 'some value'
}

// here we’re just editing `obj` in place
obj.something = 'some other value'

// ++++
// you can do it like this (ES6 syntax  )
let obj = {
    something: 'some value'
}

// this creates a brand new copy overwriting just that key
obj = {...obj, something: 'some other value'}
And same for arrays
  // ----
// INSTEAD of this:
var myStuff = [
    {name: 'henrik'}
]

// push modifies the array defined above
myStuff.push({name: 'js lovin fool'})

// ++++
// you can do it like this (ES6 syntax  )
let myStuff = [
    {name: 'henrik'}
]

myStuff = [...mystuff, {name: 'js lovin fool'}]
Now, you can just use the ​!==​ comparison to decide if you need to re-render. 
In React it would be:
  shouldComponentUpdate (newProps) {
    return newProps.obj !== this.props.obj
}

How to use this pattern?

Everything that changes anything in your app is an action.
You have one giant state object to hold all the state in your app.
You use reducers for everything that changes state. A reduce function (like ​Array.reduce()​) gets an initial state, current value and returns a new state. This is what happens with actions. Current app state is the initial state, the action changes the current value and we get a new state in return.

Actions have to be sequential. Then this pattern lets you reply all actions from a starting state. This has many implications.
Or you can just hot-reload you view components in the app, replay the reducer actions and the UI will show the new version while the state doesn't change.