This is a post that tries to explain the the basics of Redux. We’ll build a minimal working example with Redux. If you’re looking for proper Redux documentation then check official docs.

What is Redux

From the official docs - Redux is a predictable state container for JavaScript. In other words Redux is meant to handle and organize application state/data.

Here is a diagram that often is confusing when you see it first time:

Simple Redux_javascriptmore diagrams ​​here​

So let’s go step by step and see what that diagram means.

State

Simple Redux_json_02Any application has a state. Some store their state in a database, some store their state in multiple places. In Redux you store the state in a single object. It knows which page is curently open, a set of items, current user and so on. It may be normalized or denormalized, but it should know enough so that you can save the state (say as JSON) and when loaded in a different browser - it will render the same app (same page, same items, same user…).

Let’s define our state for a counter app:



var store = mobx.observable({ counter: 0 })


Rendering

Simple Redux_react.js_03Redux works very well with React.js, but it can be rendered with anything else. We’ll render the state using plain JS:



<div id="counter">-</div>



function render(state) { document.getElementById('counter').textContent = state.counter; }


Actions

Simple Redux_react.js_04If application state changes, that’s because of actions. They could be user actions, asynchronous actions, scheduled actions and so on. We’ll define a button that will trigger an action.



<button id="button">Increment</button>



document.getElementById('button').addEventListener('click', function() { store.counter = store.counter + 1 })


Store and reducer

Simple Redux_javascript_05Actions don’t change the state directly. A Redux store is responsible for that:



Js


Simple Redux_json_06The Redux store holds the current state, and reacts to actions. When an action is dispatched (line 4), the store updates the state by passing current state and current action to the reducer, and the state is updated with what the reducer returned:



Js


State change

When state changes, renderer updates the render:



mobx.observe(store, function() { render(store) })


A React.js renderer is perfect in that case as it updates only what changed (and not everything as we just did).

 

https://bumbu.me/simple-mobx/


------------------越是喧嚣的世界,越需要宁静的思考------------------ 合抱之木,生于毫末;九层之台,起于垒土;千里之行,始于足下。 积土成山,风雨兴焉;积水成渊,蛟龙生焉;积善成德,而神明自得,圣心备焉。故不积跬步,无以至千里;不积小流,无以成江海。骐骥一跃,不能十步;驽马十驾,功在不舍。锲而舍之,朽木不折;锲而不舍,金石可镂。蚓无爪牙之利,筋骨之强,上食埃土,下饮黄泉,用心一也。蟹六跪而二螯,非蛇鳝之穴无可寄托者,用心躁也。