MVVM architectural pattern for a ReactJS application - javascript

I'm a semi-senior react and JavaScript developer, I've made several Universal react application.
Today our CTO told me: Do you use a software architectural pattern for your application?
I've no answer, He points to the Android team which use MVVM for their applications.
I'm searching greedy but not found a trend methodology or example for this situation. I've used Redux, Redux-Saga, React-Context and etc.
I don't know how to explain to our CTO or what is his answer?
Hence: Does a react app really need a software architectural pattern?

React itself is not particularly opinionated about software architecture. It is a library that facilitates the reusable component paradigm alongside guidelines for managing things like state and data sharing (props). At some point, Facebook described this as the V in MVC but have since moved away from that marketing to call it more abstractly A JavaScript library for building user interfaces.
Of course, the typical tooling associated with React apps does lend itself to something of an architecture when used together.
A couple of potential ways to think about it:
Simple React apps might be just "VVM" or "VC"
MVC is probably the better-known of the two in the development world. The key conceptual difference between a controller (C) and view-model (VM) could be boiled down into: a controller can have many diverse responsibilities, like listening for events and routing them in the right direction. It's the glue that facilitates the functionality of an entire application. A view-model, on the other hand, is simply responsible for gluing the current state of the data to the model.
So Facebook's original use of "V in MVC" could probably just as easily have been "V in MVVM" - the term controller makes more sense in backend development world.
A barebones React app, without Redux, that pulls data directly into components (e.g. fetch's in componentDidMount or leveraging GraphQL) with limited data wrangling of any kind could be called a simple "VVM" model.
View-Model (VM): Component-related code that manages simple state, passes data directly onto View, potentially passes data directly back from View
View (V): How the visuals look (JSX, CSS)
Add some complexity, and you could call it "MVVM"/"MVC"
If you toss in Redux, redux-saga, or even start doing crazy things with simple React component state, you're introducing model operations. There're at least two things this Model (M) can represent:
Actual business logic for your application
Storing and managing complex behavior in your client
Business logic is sometimes undesirable in practice: for example, if you have control over the server, it might be worth keeping all your business logic in one place (on the server) and just feed the UI what it needs to interact with the user. But if you have limited REST endpoints and need to do some wrangling (e.g. in your sagas, or within components), that'll be business logic.
Client behavior management is likely, especially in complex applications where you might be doing things like displaying different things to the user based on their session (e.g. they're an unregistered user vs. user vs. admin). You're probably doing this in any redux store interactions that are contained to use by only the client.
Disclaimer: discussing MVC, MVVM, etc. is likely to lead to many different opinions of exactly what they mean [1]. Above, I tried to draw parallels between common patterns I've seen and how they fit into MVC/MVVM, but there's so many different ways to approach it or more granular ways to think about it. I wouldn't get too hung up on putting a label on it as long as your system is easy to understand: modular, DRY, abstracted, etc. at levels that make sense for your use case and scale of development.
[1] Discussed in the some more length in answers and comments to this question

Vue 3 is MVVM:
Proxy Update
Model → ViewModel → View
Model ← ViewModel ← View
Update Event
And React:
setState Update
Model → ViewModel → View
Model ← ViewModel ← View
Update Event
The difference is only how the frameworks notify Model changes to the ViewModel.

A simple Web App does not require MVC, MVVM, does not require even React IMO.
Possible evolution of a simple ReactJS App that may see the need of MVVM/MVC/ if it tries to be PWA (Progressive Web App). In other words - if it tries to do some (application/domain) specific logic - offline and some other - online. This is natural point of thinking for mobile app development. Then, the information may be retrieved from the Local Storage or the IndexedDB (for the Web) or the Back-End/Rest/. Then, the separation of Model, Storage/Repository/Source Of INfo/ ViewModel/ or Controller/ and View will be natural and actually needed for all stuff to work correctly...

Related

Is Redux.js a sufficient way to separate data from view in a React.js/Node.js hybrid application?

I am quite new to web programming. I've started developing a single-page web application using React.js with a Node server.
I've read the tutorial, played with boilerplates, and quickly I understood React would take care only of the view aspect. So I tried to put my data-processing functions with the export keyword in a JavaScript file so I could use them in my React components. But that way was pretty "dirty" and it didn't feel satisfying at all.
Then I looked for a way to effectively separate the model and the controller from the view, so that I could completely change the GUI with little effort, and thus allow the project to grow and multiple people to work on it at the same time.
I've came across this article explaining the Flux architecture, and I saw a major implementation to use with React.js was Redux.js. I was quite surprised that I didn't see it at first, and now I wonder how much frameworks one has to use when working with JavaScript and Web.
My question is simple : is Redux.js all I need to effectively separate data, treatments and GUI components ? Or did I miss something else ? Are there any other major architectures you would recommend ?
Many thanks,
Redux is generally used to contain all the data that your app needs. It acts like a store which can pass the required data to the components that actually needs the data. For example, if you need a particular data fetched from an ajax request to be distributed among two components, then redux is a perfect fit. Whether you need redux depends on how your app is structured. If you have an app with a large number of components and most of these require data from your server or api, I'd suggest you go with redux. Once you learn it, it's incredibly simple. And yes, redux is all you need to separate data from ui. To get a nicely formatted structure, put together all your ajax requests under a folder and export it so that you can call it from the ui component. And when you receive the data pass the payload to the redux store which will automatically pass it to all the components which are connected to that particular reducer. For details on how to connect react with redux, check out their documentation:
https://redux.js.org/basics/usage-with-react
Remember not to confuse the state mentioned in redux with the state in react. Redux state refers to the application state. Do check it out and if doesn't work for you, another alternative would be flux.

State management of angular 2 application

I am new in Angular2. Angular provides various options for managing the state of an application like ngrx/store, angular services etc. if we manage the state of the application using ngrx/store then we require an external library but in case of angular services do not require. What should be used for managing the state of an application? what are the pros and cons of each approach? Is there any recommendation that is provided by the angular community?
You do not need ngrx/store to implement a redux-store. You can implement one yourself. There are multiple tutorials online showing how to do it in a lightweight way. But ngrx/store is developed and supported by people from google and so it is a mature framework you can trust, which also provides some neat features, like effects for asynchronous events and immutability checks in development.
The main question is whether or not you should use the redux pattern/store in general. This highly depends on your application architecture. For smaller applications it could be too much work, especially if you don't have clear user stories and things might change quickly.But i f you have a big SPA, in general it is recommended to use a central data flow store, e.g. redux. It ensures the dataflow in your application is unidirectional and there are no circular dependencies at important parts of your application, causing weird bugs in the future as your application gets more complex.
Also even in a SPA you have things like UI-Libraries which do not belong in a store. A button prototype being enabled or disabled is something only its component should be aware of. But the same button in usage in the application module should represent a particular functionality being offered or not and that should be represented in redux.
I highly suggest you look at the ngrx-store example app and see the benefits and shortcomings yourself.

Improve Angular performance: change the view to reactjs or Mithril?

I have a performance issues with Angular (as many others). I wish to change only the view layer to either reactjs or Mithril. I found examples of React js (for example http://www.bimeanalytics.com/engineering-blog/you-put-your-react-into-my-angular/), but not of Mithril.
Can anyone advice to the pros and cons of using Mithril as an angular view vs Reactjs?
Thank you!
I don't think there's an objective answer here, and as a Mithril user I have my biases, but here is what I think.
In terms of philosophy, Mithril and React are quite similar: you write view functions that describe how your app should look at any given time. In terms of rendering performance, I don't think there's a clear winner. There are links / blog posts that say Mithril is faster than React, and vice versa.
So instead what I think you should focus on is:
1) Which API do you prefer? With React you should use JSX lest you have to reverse engineer their documentation. Mithril also just has one lifecycle hook (the view function), whereas React has several (such as shouldComponentUpdate) -- do you need all those hooks?
2) Community support -- React is the clear winner here, and the fact that there are existing examples of integration with Angular is a win.
3) Compatibility - DOM redrawing / diffing in React is done when data changes, just like Angular, but Mithril's redraw is centered around user interaction (such as clicks, route changes, ajax requests). You can manually redraw, but that's less desirable. I don't know how well Mithril will fit into an Angular setup.
Should you decide to use Mithril, I'd encourage you to use the Google group (https://groups.google.com/forum/#!forum/mithriljs) as a resource, or at least report back on your experience.
Mithril and React have many similarities. I've used both of them and here are some pros and cons.
Mithril
Pros: It's loading times are very fast. This is because it's templates are compiled first and then served to the browser. You can write Mithril views in JavaScript. Small size, good documentation and doesn't force you into a predefined structure.
Cons: Small API can make it unsuitable for larger more complex projects.
ReactJS
Pros: React's one-way data binding means that it's easy to see where and how your UI is updated and where you need to make changes. It also provides server-side rendering, virtual dom support, good debugging tools, easy to write tests, easy to reuse components, flux architecture patterns, and extensive SVG supports etc.
Cons: Heavy on memory compared to Mithril, not a complete solution as it mainly focuses on the view, and need to learn a new syntax etc.
In my view, React is overall preferable. But, if your application doesn't need all these extra stuff that React provides, you should go with Mithril.

Is Flux a library which operates as the backend for React?

I'm very new to the React and Flux consept and I'm confused as hell..
I come from a background of Sails.js so I can't really tell whats what with React.
I plan to use Sails.js (as a restful api, isolated from the front end)
+
React (as my front end using restful calls + perhaps websockets to communicate with sails)
but I don't see where flux fits in!
No.
Flux is a design pattern, rather than a framework or library. You can use Flux without using React and vice versa, although they are optimized to work well with each other.
Flux applications have three major parts: the Dispatcher, the Stores, and the Views (not be confused with Model-View-Controller). EventEmitter is typically used as a basis for Stores and React as a basis for Views. The one piece of Flux not readily available elsewhere is the Dispatcher, although you could write one yourself if you want.
Controllers do exist in a Flux application, but they are controller-views -- Views often found at the top of the hierarchy that retrieve data from the stores and pass this data down to their children. Additionally, action creators — dispatcher helper methods — are often used to support a semantic dispatcher API.
Flux eschews MVC in favor of a unidirectional data flow. When a user interacts with a React view, the view propagates an Action through a central Dispatcher, to the various Stores that hold the application's data and business logic, which updates all of the views that are affected. While you don't need React to implement this pattern per se, it is designed to work especially well with React's declarative programming style, which allows the store to send updates without specifying how to transition views between states.
More info can be found at the official Flux repo.
Flux is definitely not a requirement for using React and does not operate as a "back-end" for React. It's just a common pattern for structuring applications written with React. It's well documented here.
It is only a client side solution. It does not have a hard requirement on any particular web server (but it is convenient if you have NodeJS installed so that you can use something like Browserify to compile and package scripts).
It's not clear from your question what parts of Sails you're planning to use. If you want to use React in an isomorphic way (meaning you'd run React code on the web server and it would be then "attached" by the React client code, without re-rendering), then data management could be an issue if you're using Waterline. But, if you're only going to use React on the client, then it may be an easier integration.
But, again, it's not necessary to use Flux. You can just follow the basic principles of using React JS regarding data flow (parent to child) and use other data storage and synchronization libraries. React is not opinionated that way.
Also, while Facebook has a Flux implementation here, you'll find dozens of implementations of the pattern with various tweaks and enhancements located here. You'll also note on that same page that there are lots of other complimentary libraries that may be useful.

Implementing 1-page JavaScript web app using the principles of MVC

How would you implement this app in JavaScript using principles of MVC?
As you can see, the app basically has 3 views: "Sidebar", "Visualization" & "Timeslider". The underlying model must keep track of selected countries and year.
When initing the app, it should load a json file that populates the model with data. With some sort of event system (please advice), the controller should be notified of a stable model, and corresponding views should be set.
For example, adding a country in the sidebar should trigger data reload, followed by updating of x/y scales of the visualization view to accomodate for more countries etc.
How would you separate the logic from the views (what would go in the model, view & controller respectively) and what libraries would you use? (especially re. event handling).
Code is much appreciated ... Thanks.
For this kind of application I suggest you to look into backbone.js.
Which basically is:
Backbone supplies structure to
JavaScript-heavy applications by
providing models with key-value
binding and custom events, collections
with a rich API of enumerable
functions, views with declarative
event handling, and connects it all to
your existing application over a
RESTful JSON interface.
You can take a look at Views on the backbone.js documentation; they have a huge amount of examples for you available, which will be more helpful than me providing a complete solution using backbone.js. They also have several demos with fully built apps ready fo you to base off.
Update: Also take a look into spine.js which is really similar to backbone but it's not the same, from their F.A.Q the difference is:
Whoah - your API looks really similar to Backbone. Why should I use this Instead?
Well, it's true that Spine
was inspired by Backbone, an excellent
library, and its controller API is
very similar. However, the
similarities end there. Internally the
library works very differently. For
example, Spine has no need for
Collections, which are required for
pretty much every model in Backbone.
Spine provides a class library, and
has very different ideas when it comes
to server sync. Lastly, Spine is much
simpler and half the size, go and
check out the source.

Categories