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

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.

Related

When ReactJs is appropriate

From what I have been researching, ReactJS is the new craze in the world of front-end development. I can find few articles that are able to provide a bias free look on ReactJS. There is only praise for it, but should it be used everywhere? I know an html.erb file with javascript can accomplish what ReactJS can do. Everything has its place. Where does ReactJS and React Native fit in? Specifically when should they be used? I know JavaScript can handle a lot, but of those things it probably shouldn't handle, or there is a better solution.
I would greatly appreciate guidance on these questions.
React has many cool features and is one of the best libraries for using for building UI apps
it utilizes something called the virtual dom to enhance performance in applications
it has a really intuitive pattern with storing state in local components which can be passed down to children components as props.
it integrates well with state management frameworks like Redux (there is a helper package called react-redux which makes the integration seamless) but it also has it's own context API which can be used for wider ranging state
it recently introduced the concept of hooks. these replaced lifecycle methods which were popular in previous versions and are now a cool way to "hook" into components and utilise functionality whilst the component mounts and unmount
of course, like with everything, there are alternatives. you can just use plain old vanilla which has it's own benefits or you can choose a popular alternative such as Vue.js.
There is no hard and fast rule specifically when it should be used. the ball is in your court

MVVM architectural pattern for a ReactJS application

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...

ReactJs in AngularJs

As I don't know anything about React jet, I am wondering, what are the main benefits of introducing React in Angular's directives and what are down sides?
Basically I am working on some complex software with lot's of renderings in one cycle. Obviously I already excluded ngRepeat, etc. but I am wondering if React can speed up rendering in this case even further?
Is react better only in rendering lot's of element's or is it better in rendering of small amount of them as well?
That's a subject I've studied at work and here are my conclusions about adopting an hybrid solution (AngularJS 1.x and React) :
Pros :
best of both worlds (speed, testability, a lot of convenient things already are implemented in AngularJS — $http, $cookies, whatever)
probably forces to uncouple more and more the code. Since the two worlds can't really share components/services, you'll have to adopt a nice architecture which will lilely makes the two parts easy to plug/unplug. Say you wanna use Angular2 components after all, a lot of uncoupling work will already be done.
Cons :
You'll have to glue stuff together. The glue code can end being more complicated than expected
You'll have to load two frameworks/libs. Although that might not be a problem for SAAS apps, it can very well be for regular websites with a lot of unique visitors.
You'll have to learn another framework (should that be in the "Pros" section ?)
Maintainance bad smell : the less different technologies, the better
An overall more complicated stack
In the end I think that if you don't absolutely need React, try to implement your component in regular JavaScript to avoid excessive $apply cycles. It's cleaner in my opinion.
You can take a look to this link. This video was recorded last year in the ng-conf and explains how you can speed up your angular application rendering certain elements with react.
I think it can help you.

Working with Angular 2 [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Our team is way too excited with the alpha release of Angular 2 and we're just eagerly waiting for it's stable release and getting started with it.
But during the ng-conf 2015 on Angular 2 by Misko, we came across following things which made me confused
TypeScript! Is it really needed to use typescript to gain better performance instead of writing plain simple JS code we've been doing all along. We've came across a few comments that says typescript helps in better performance.
ES6 features. Since angular 2 will be using a lot of es6 features, would that mean we'll have to wait for all the browsers support at least those features needed by angular 2 before we can kick start with it on our production applications.
Web components. Since angular 2 provides the facility to create web components and I've came across a few blogs on creating your own (using polymer), how hard is it gonna be for our team to create them? Or is it better if we just stick to old directives creation thing ?
Performance. I've seen this video of Angular + React which provides a good comparison of angular vs angular + react vs angular 2. But I'm not sure if that's the case that angular 2 is really fast all the way or if we can go ahead with building angular + react app to avoid waiting for angular 2 to stabilize or the browsers to have support for es6 features that angular uses.
I'm not sure I've structured my question well, but above are my concerns before I start learning angular 2 because with their demonstration of angular 2 + typescript seemed like it's gonna involve a lot of earning curve for me and my team.
I'll really appreciate if someone can clarify on the above listed concerns I have.
Thanks.
TypeScript! Is it really needed to use typescript to gain better performance instead of writing plain simple JS code we've been doing all along. We've came across a few comments that says typescript helps in better performance.
TypeScript is about static analysis for better type-safety. It also has a pretty nice suite of editor tools (e.g. WebStorm). You don't need it for performance. It's more a tool for helping you author. Personally though, I love it.
I've begun migrating some of my existing open-source libraries to TypeScript because it's so much easier to work with. For example, check out Task Runner before and after.
ES6 features. Since angular 2 will be using a lot of es6 features, would that mean we'll have to wait for all the browsers support at least those features needed by angular 2 before we can kick start with it on our production applications.
A lot of ES6 features can be polyfilled. Check out https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills.
Web components. Since angular 2 provides the facility to create web components and I've came across a few blogs on creating your own (using polymer), how hard is it gonna be for our team to create them? Or is it better if we just stick to old directives creation thing ?
Web components are also polyfillable (see here). In this case, I'd suggest you follow the Angular team's recommended practices for creating your components. Also perhaps keep an eye on what's coming out of the Polymer team in this regard.
Performance. I've seen this video of Angular + React which provides a good comparison of angular vs angular + react vs angular 2. But I'm not sure if that's the case that angular 2 is really fast all the way or if we can go ahead with building angular + react app to avoid waiting for angular 2 to stabilize or the browsers to have support for es6 features that angular uses.
This sounds to me like premature optimization. Build for (plain) Angular first and optimize only if you notice performance problems in particular parts of your application.
TypeScript! Is it really needed to use typescript to gain better performance instead of writing plain simple JS code we've been doing all along. We've came across a few comments that says typescript helps in better performance.
TypeScript is not required to use Angular2.
Most examples you see will use JavaScript:
classes (ES6)
decorators (ES7/Typescript)
types - (Typescript)
Except, browsers don't support those features yet so all Angular2 source will need to be transpiled to ES5.
So in ES5:
classes can be faked by extending prototypes
decorators can be faked using wrapper functions
types aren't really necessary to begin with, they're synctatic sugar added for safety
It would be unrealistic to expect existing users to inherit the risk of using experimental/bleeding-edge standards. As such, the documentation covers writing Angular2 apps in ES5, ES6/7, and Typescript.
Aside: I personally prefer not to use TypeScript. Traceur can be configured to support with experimental extensions for #decorators, and system.js provides a polyfill for the proposed es6-moduler-loader spec.
Here's a look at the Angular2 Documentation.
ES6 features. Since angular 2 will be using a lot of es6 features, would that mean we'll have to wait for all the browsers support at least those features needed by angular 2 before we can kick start with it on our production applications.
As I said already, ES6 isn't officially supported yet in all browsers. Even if it were, most sites will still require a polyfill to provide backwards compatibility to older browsers.
One of the cool features of the es6-module-loader is the ability to dynamically load dependencies on the fly. By the time Angular2 is out of beta, it should be easy to incorporate this into your app as a feature-detection strategy.
Web components. Since angular 2 provides the facility to create web components and I've came across a few blogs on creating your own (using polymer), how hard is it gonna be for our team to create them? Or is it better if we just stick to old directives creation thing?
Not hard although you may need to use Angular2-specific web components. The reason being, Angular2 is more than a front-end web framework. It's can also be used for isomorphic (ie prerender on the back-end), native, and mobile apps. That means, touching the DOM directly is highly discouraged.
As for the creation of the components themselves... It's no different than creating any other component in Angular2. Unlike the old MVC model of grouping code by type (ie models, views, controllers), the component model encourages grouping code by context.
When you import a reusable component, it should come with any directives, services, etc required to use it.
For an example, see the I created. In addition to cloning the repo directly from GH, the code can be installed and imported directly via JSPM.
Simply import it, add the component class to your view directives and any <ng2-markdowm> element in your template will just work. It doesn't get much easier than that.
Performance. I've seen this video of Angular + React which provides a good comparison of angular vs angular + react vs angular 2. But I'm not sure if that's the case that angular 2 is really fast all the way or if we can go ahead with building angular + react app to avoid waiting for angular 2 to stabilize or the browsers to have support for es6 features that angular uses.
There are 3 major performance improvements introduced in Angular2.
1. 2-way data binding is no longer the default
Elements that require data binding need to be explicitly marked in the template (ie don't fret, the new syntax makes this really simple). As a result the overhead required to do dirty checking on the DOM is dramatically reduced.
That means, no more $scope, $scope.apply(), and weird scoping rules in the HTML markup. Instead, the hierarchy of custom <elements> is defined in the Angular2 components.
2. Angular2 leverages the virtual DOM
jQuery made it extremely simple to directly manipulate the DOM. As a result, it also made it extremely easy for inexperienced developers to thrash the DOM and trigger layout reflows via frequent incremental updates.
The VDOM is basically a simplified in-memory representation of the DOM. Incremental updates get applied directly to the VDOM which later get applied to the actual DOM in batches.
Aside from network requests, DOM manipulation is JavaScript's greatest performance weakness. The VDOM on the other hand is an order of magnitude faster. Instead of expecting devs to follow 'best practices' by manually batching updates to the DOM, Angular handles batching transparently.
Fewer DOM manipulations = less UI rendering/reflows = a much more responsive user experience.
3. Angular2 runs on a background worker
This isn't exactly a new concept. Desktop GUIs have worked this way for years, it just wasn't technically possible the introduction of HTML5 background workers.
In most desktop applications, the main context runs synchronously+ and the UI runs asynchronously in it's own separate thread. That makes the user experience responsive regardless of whatever the application is doing in the main context.
+Note: This isn't necessarily true, but for clarity sake.
In the browser, all execution happens in the main context+. That means, every time Javascript has to block on a CPU-heavy operation, the user interface becomes unresponsive to the user. This is not ideal and makes for a lousy/inconsistent user experience.
+Note: In practice browser implementations vary greatly but lets keep things simple.
With web workers, it's possible to push everything but the DOM+ into a background worker context. Ideally, Javascript's should have little-or-no impact on UI responsiveness.
+Note: The DOM's state still needs to be accessible to the renderer.
One side-effect this transition is, the Angular2 architecture is now completely decoupled from the UI/DOM. Meaning, it's now possible to write UI adapters for other platforms (ex for IOS, Android, SmartTVs, etc) that run on the same Angular2 code natively.
React
As far as I can tell React is using all of the same performance improvements as Angular. They use the VDOM to batch updates, and mentioned native portability to other platforms so I assume they went through the same architectural change as Angular.
Honestly, using background processing to free up the UI is just another step in the evolution to reach feature parity with desktop applications.
Angular2 vs React
I encourage you to watch the video again all the way to the end. The presenter screwed up when he wrote the code so the live demo wasn't an honest comparison.
With that said, it doesn't really matter which is faster. Neither will be dramatically faster than the other but they'll both be dramatically more responsive and scalable compared to other UI frameworks.
Update:
Rewrote the section about web components to better answer the question.
Note that Angular 2.0 does promise to work well with Web Components and Polymer, but in the current stage, i.e. Angular 2.0 alpha, it doesn't work (see this). So you'll have to wait for a while I guess.

Architecture of a single-page JavaScript web application?

How should a complex single-page JS web application be structured on the client-side? Specifically I'm curious about how to cleanly structure the application in terms of its model objects, UI components, any controllers, and objects handling server persistence.
MVC seemed like a fit at first. But with UI components nested at various depths (each with their own way of acting on/reacting to model data, and each generating events which they themselves may or may not handle directly), it doesn't seem like MVC can be cleanly applied. (But please correct me if that's not the case.)
--
(This question resulted in two suggestions of using ajax, which is obviously needed for anything other than the most trivial one-page app.)
MVC architecture of PureMVC/JS is the most elegant IMO. I learned a lot from it. I also found Scalable JavaScript Application Architecture by Nicholas Zakas helpful in researching client side architecture options.
Two other tips
I've found view, focus, and input management are areas that need special attention in single page web apps
I also found it helpful to abstract away the JS library, leaving door open to change mind on what you use, or mix & match should the need arise.
Nicholas Zakas's presentation as shared by Dean is a very good place to start with. I was also struggling to answer the same question for a while. After doing couple of large scale Javascript products, thought of sharing the learnings as a reference architecture in case someone needs it. Have a look at:
http://boilerplatejs.org/
It addresses common Javascript development concerns such as:
Solution structuring
Creating complex module hierarchy
Self contained UI components
Event based inter module communication
Routing, History, Bookmarking
Unit Testing
Localization
Document Generation
etc.
The way I build apps:
ExtJS framework, single page app, every component defined in a separate JS file, loaded on-demand
Every component contacts its own dedicated web service (sometimes more than one), fetching data into ExtJS stores or special-purpose data structures
The rendering uses standard ExtJS components, so I can bind stores to grids, load forms from records, ...
Just choose a javascript framework, and follow its best practices. My favorites are ExtJS and GWT, but YMMV.
Do NOT roll your own solution for this. The effort required to duplicate what modern javascript frameworks do is too big. It is always faster to adapt something existing than to build it all from scratch.
Question - What makes an application complex ?
Answer - The use of word 'complex' in the question itself. Hence, a common tendency will be to look out for a complex solution right from the beginning.
Question - What does the word complex means ?
Answer - Anything that is unknown or partially understood. Example : The theory of Gravity even today is COMPLEX to me but not to Sir Isaac Newton who discovered it in 1655.
Question - What tools can I use to deal with complexity ?
Answer - Understanding and simplicity.
Question - But I understand my application . Its still complex ?
Answer - Think twice, because understanding and complexity does not co-exist. If you understand a huge huge application, I am sure you will agree that it is nothing but an integration of small and simple units.
Question - Why all of the above philosophical discussion for a question on
Single Page Application (SAP)?
Answer - Because,
-> SPA is not some kind of core technology that is newly invented for which we need to reinvent the wheel for a lot of things that we are doing in application development.
-> Its a concept driven by the need for better performance, availability, scalability and maintainability of web applications.
-> Its a fairly newly identified design pattern, so an understanding of SPA as a design pattern goes long way in making informed decisions about the architecture of a SPA.
-> At the root level no SPA is complex, because after understanding the needs of an application and the SPA pattern, you will realize that you are still creating an application, pretty much the same way you did before with some modifications and re-arrangements in the development approach.
Question - What about the use of Frameworks ?
Answer - Frameworks are boiler plate code / solution for some commonly identified and generic patterns, hence they can take off x% (variable, based on the application) load from application development but then not a lot should be expected out of them specially for heavy and growing applications. Its always a good case to be in complete control of your application structure and flow but most importantly the code for it. There should be no grey or black areas in the application code.
Question - Can you suggest one of the many approaches to SPA architecture ?
Answer - Think of your own framework based on the nature of your application. Categorize application components. Look for an existing framework that is close to your derived framework, if you find it then use it, if you do not find it then I suggest going ahead with your own. Creating framework is quite an effort upfront but produces better results in long run. Some basic components in my SPA framework will be:
Data Source : Models / Collections of Models
Mark Up for presenting data : Templates
Interaction with the application : Events
State capturing and navigation : Routing
Utilities , widgets and plug-ins : libraries
Let me know if this helped in any way and good luck with your SPA architecture !!
The best thing to do is to look at example uses of other frameworks:
TodoMVC showcases many many SPA frameworks.
You can use javascript MVC framework http://javascriptmvc.com/
The web application that I am currently working on uses JQuery and I would not recommend it for any large single page web application. Most frameworks i.e. Dojo, yahoo, google and others use namespaces in their libraries but JQuery does not and this is a significant drawback.
If your web site is intended to be small then JQuery would be ok but if you intended to build a large site then I would recommend looking at all the Javascript frameworks available and deciding which one most meets your needs.
And I would recommend applying the MVC pattern to your javascript/html and probably most of your object model for the javascript could be done as the json that you actually return from the server through ajax and the javascirpt uses the json to render html.
I would recommend reading the book Ajax in action as it covers most of the stuff you will need to know.
I'm using Samm.js in several one page applications with great success
I would go with jQuery MVC
Check out http://bennadel.com/projects/cormvc-jquery-framework.htm Ben is pretty sharp and if you dig around on his blog he has some nice posts about how CorMVC is put together and why.
Alternative: take a look to ItsNat
Think in JavaScript but code the same in Java in server with the same DOM APIs, in server is way easier to manage your application without custom client/bridges because UI and data are together.
Or have a look at https://github.com/flosse/scaleApp
NikaFramework allows you to create single-page application. Also allows you to write HTML, CSS (SASS), JavaScript into separate files and bundle them into only one output file in the end.
I would recommend to explore Yeoman. It allow you to use existing "best practice" for your new project.
For example:
if you decide to use Angular.js, there is a Yeoman generator, that give you a structure for routing, views, services, etc. Also allow you to Test, minify your code, etc.
If you decide to use Backbone, checkout this generator

Categories