Tag: pattern

From MVC to Redux

From MVC to Redux

If you come from MVC or one of its brothers/cousins/incredible mutations, this diagram should be familiar to you:

Mvc to redux: MVC worflow

The user action triggers a call to a controller, who updates the model and refreshes the view.


This works well when you have few controllers and views, but it gets really messy as the application’s complexity increases. The complete model is exposed through several controllers, so you will need to orchestrate calls from one controller to another, making it really hard to tell where a certain change came from or which is the complete state of the application at a specific point.

The fact that views make asynchronous calls to this controllers will add an extra difficulty to your confused and ephemeral life and then you will be ready to love Redux:

Mvc to redux: Redux worflow



In Redux, the state is an object that contains the whole model of your application, like a big tree with all your application’s data. This object has no setters, as you cannot modify the state directly. Did you see where state sits in the diagram? It can only be accessed by the Reducers.

Instead of setting properties in the state, each component can dispatch actions to the store and those actions will be translated into state changes.

The actions are plain javascript objects also, describing the intention of modifying the state, like:

{ "UPDATE_COMPANY", company: newCompanyData } 

The reducers are a set of chained functions that take this action and the current state and return a new complete state tree.

reducer(oldState, // { user: user, company: null}
  action);        // { "UPDATE_COMPANY", company: newCompanyData } 

//returns new object { user: user, company: newCompanyData }

Once the reducers have been executed, the Redux store saves this object as state, and every component listening to the store changes will now be updated.

Like in the CQRS pattern, the model used to update information(dispatch an action) is different than the model used to read it (subscribe to store changes).


-As you are holding the state in a single object, you can recreate the state easily and the application becomes much easier to test.
-As the reducers are pure functions (they always return the same output for a given input), you can undo and time-travel the states, which helps a lot with debugging.


More on…

Redux basics: https://redux.js.org/basics/actions

Event sourcing: http://microservices.io/patterns/data/event-sourcing.html

CQRS: https://martinfowler.com/bliki/CQRS.html

Unidirectional UI: https://staltz.com/unidirectional-user-interface-architectures.html

Thinking in Redux: https://hackernoon.com/thinking-in-redux-when-all-youve-known-is-mvc-c78a74d35133