ASP.NET MVC and Redux

When we at Spoil decided to roll out our mobile app, one of the first decisions we had to make was: what language do we use? After some deliberation, the decision was made: React-Native it was going to be. Learning a new “language” or framework isn’t a huge issue. 

React-Native and Redux?

As soon as you start learning about react-native (or react), you start to understand state vs props, you know what componentDidMount does and you even understand how to properly create your components so they are re-usable. Now all of a sudden you found yourself talking about stores, reducer compositions, actions and mapping state to props.

Some Analogies

If you are coming from an MVC (or MVVC) world, you are used to models, views and controllers. However in Redux we are dealing with actions, reducers, stores and components. Trying to “translate” MVC to Redux is tricky but here is how I would do it:

Actions = Controller. Think of your actions as the controller. Whenever you want something to happen in your app (i.e. load some data, change a isLoading flag from true to false…) you will have to dispatch an action. Just like in MVC where you would have to call a controller endpoint.

Reducer = Model. Sort of. Your reducers will be in charge of holding the current state of your application (i.e. user info, information loaded from the api, items you want to display…). It will also be the part that decides what to do when an action is called. While in MVC you might have a model with the method setName(), with Redux you would have a reducer handle an action to set the name in the state.

Stores = ???. The store is Redux specific and doesn’t really have an equivalent in MVC. Not to worry though. This part is taken care off behind the scenes. The store is like a container for the state that aggregates all of the reducers. It has a method to the get the current state, and exposes ways to subscribe to the state changes (using the “connect()” method). This is what will allow you to call actions and pass them in as props to your components.

Components = Views. Components are kind of like your smart views. They display the information that they get from the state. I recommend splitting up your components into two parts. One just for the presentational part (dumb components) and one to handle all of the actions and state changes (smart components).

Moving From MVC Thinking to Redux Thinking

One of the main differences between MVC and Redux is that, while in MVC data can flow in a bidirectional manner, in Redux it strictly moves in one direction.

With Redux things work a little differently. Let’s say you have a component and you want to do something when a button gets pressed. Where do you start? 

  1. Define your Action
  2. Define your Reducer
  3. Define the Actions as a Prop in your Component
  4. Wire it up in your View

 

Copyright © All Rights Reserved - C# Learners