Angular vs. React - the tie breaker

转载 2015年07月10日 09:19:08

原文 https://www.airpair.com/angularjs/posts/angular-vs-react-the-tie-breaker


1. Introduction

A short while ago, our team had to choose a technology for Wix's flagship product, the html wysiwyg website editor. It is a large single-page application, with complex flows, communication with other iframes and servers, and a lot of user experiences. This product is developed by more than 40 developers. The choices were ReactJS or AngularJS. We had experience with both, and were struggling between the ease-of-use of Angular declarative programming and the simplicity of React. We started a proof of concept that ultimately drove us to form a tie breaker. This article is about the comparison… and the tie breaker.

1.1 Packaging

Packaging is the ability to run and deploy your code in the way you want it. In order to achieve fast loading time, we want to load the bare minimum at first and continue on demand. This also gives us the ability to continue to develop new features without slowly degrading the load time.

Angular provides a very limited ability to do so (mostly html templates) and when we tweaked it to do what we wanted, it looked like assembly code.

In short, we found Angular to be too opinionated and too rigid. React doesn't care, it's plain JS and allows us to use requirejs to lazy load pieces of code. It also allows for working with other solutions like webpack.

Winner: React

1.2 Learning curve

Everybody knows about the bumpy road to mastering Angular: it's quick to get started, then it improves and deteriorates as you go along, a lot like marriage…

We found that you can learn React to a high standard in just a week. It takes some time to get used to the one-way flow, especially for web developers, but once you do, it's very lucid.

The lifecycle of Angular is complex, and to master it, you really need to read the code. Compile and link are not intuitive, and specific cases can be confusing (recursion in compile, collisions between directives). React, on the other hand, has only a few lifecycle methods, and they are self explanatory. The best feature we found with React is that never, even once, did we have to read its code.

Winner: React

1.3 Abstraction

Good abstraction is priceless. Abstraction provides fast development and hides details that are not necessary for the developer using a library.

We found Angular's abstraction to be leaky. This means that in order to actually work with it, you need to understand the underlying model. This is why so many people need to debug the internals of Angular when debugging their code.

There are concepts that are exposed in order to treat the leaks, for example, directive priority. But how do I control priorities when using directives from different 3rd party vendors? Why should I care? Why is it that different directives sometimes don't work nicely together on the same html node? Why do I need to know about digest cycles?

React's abstraction results in it being less flexible in parts, like not being able to add attributes to html tags, or a single tag for a component. This is solved by React's implementation of mixins (that allow overlap only on lifecycle methods, and have a predictable execution order) and the fact that it doesn't leak (like I mentioned above, we never had to open it's code).

Winner: React

1.4 Model complexity

By model complexity, I'm referring to how you structure the data model that is later represented by the view.

Angular's performance is sensitive when dealing with scope because of copy-n-compare. This means that you cannot use large models. This has pros and cons. Pros, as it makes the code simpler and more testable; but cons, as it forces you to break down stuff that you'd normally use, and rebuild it back up (for server request for example).

React gives you the freedom to choose, without the performance penalty. The outcome really depends on whether you're a good coder or a bad coder.

Winner: tie

1.5 Debugging

When something doesn't work, we all start the tedious task of debugging. I'll separate this into two main scenarios - figuring why your logic is not working, and understanding the outputted HTML along with what generated it.

Angular is an event driven system, which is always easier to write and harder to debug as the stack-traces end up longer and different than what you'd expect. However Angular does a good job of providing constructs that are logical, like services. If used correctly, they make the code easier to test and debug, but any good programmer will try to separate code and logic with or without them.

When something doesn't work in Angular directives, one option is to re-write the code in a different way because there's so much magic going on. Another option is to debug Angular's code - not a trivial task.

React has two main scenarios - updating the model/doing other actions as a result of user events; and the one-way rendering flow which is always the same. This means that there are fewer places to look for your bugs and the stack traces have clear distinction between React's code, and your own. They normally don't mix. React also has less magic, and it's all concentrated in one place - the vDom comparison. It is a closed black box but in our experience, it worked as expected.

When talking about understanding the HTML, and back-tracing to the code, the story is the opposite. In React, it is hard to compare your code to the resulting HTML. Even when using jsx, you can hardly compare them as "if" and "repeat" control flows break the HTML fragments into tiny chunks of templates. In Angular, however, the result closely resembles the HTML template.

Winner JS: React Winner HTML: Angular

1.6 Binding

In Angular, you can only bind to scope. This means that in complex scenarios like binding to a server/async service, or when binding to a large model, you will need to have an intermediate model in the way, plus you will need to deal with digest cycles and with explicit watches.

In contrast, React only provides syntactic sugar for binding that is called valueLink (a single attribute for both "value" and "onChange" properties). This concept is so simple that it doesn't sound like it will do the job, yet it does. And if you understand it well, you will be able to create your own linkState or similar functions that will answer all of your binding needs.

Winner: React

1.7 Performance tweaking

React makes it simple to control the performance. If you implement shouldComponentUpdate, you can choose which comparison you prefer - model or presentation. If your model is small, just let React do the comparison on the vDom. If your model is complex, or you create a lot of DOM, you can optimize it by a custom implementation of this function, where you can devise your own mechanisms for dirty-checking that can be very efficient.

In Angular, however, you need to start counting scopes (there are numerous utilities that do it for you), and in some cases, you just have to implement the internals of a component in pure js and wrap it in Angular for convenience. The evidence of this is the amount of articles you can find about Angular performance tweaking…

Winner: React

1.8 Code re-use

Angular gets points for having sooo much stuff ready for it out there, however it's not trivial to use Angular libraries from more than one provider due to namespace and priority collisions. React lets you manage it the way you like. Saying that, Angular is still stronger in the market and has more ready-made stuff to offer.

Winner: tie

1.9 Templating

I saved the most important one for last… Even though most of the Angular or React articles discuss directives or data-flows, the reality is that when writing an online service, 80% of what you are doing is writing UI. I call them panels, the building blocks of application logic. They contain a lot of information and custom flows, and are built using ready-made building blocks, but they are not generally re-usable, and they are the bulk of what our users see and interact with. React does poor job with those. When writing a repeater it will look backwards:

var createItem = function(itemText) {
    return <li>{itemText}</li>;
};
return <ul>{this.props.items.map(createItem)}</ul>;
Like learning from posts like this? Subscribe for more!

Whereas in Angular it will look like:

<ul>
    <li ng-repeat="item in items">{{item}}</li>
</ul>
Like learning from posts like this? Subscribe for more!

How much better is that? (Answer: a lot). So Angular is a clear winner in this section.

Winner: Angular

2. The tie-breaker - React-templates

So, how do we resolve this debate? How can we get all of the benefits of React stated above, but not miss out on this great, super-important feature of Angular? We decided to give it a go and solve it for React.

The design consideration for the tool were:

  • Any valid HTML file is a valid reactTemplate, almost. We keep event notation camelCase like React, and also the notation for no-value attributes like disabled (true/false values will determine whether they appear in the actual DOM)
  • Switch from html context to js context with curly braces, and inside directives
  • Conversion should not be in runtime, so it doesn't affect performance. No additional objects for scope or runtime code, use only js native constructs (closures, methods, native expressions) to achieve this functionality
  • Make the generated code as human parse-able as possible
  • Directives are inspired by Angularjs and should be obvious to people with prior Angular experience
  • Keep it small and simple. Directives need justification to be added (the entire converter is 350 lines of code)

And the result is the amazing React templates. We've got all of Angular templating values with the simplicity of React! We get complete separation between presentation and logic, declarative writing of panels, and to make it even more useful, we've added module loader support (either AMD or CommonJS) to allow reuse of other components within the templates themselves. Let's see a few examples to show how simple this is.

2.1 Collection iteration

<ul>
    <li rt-repeat="item in items">{item} at index {itemIndex}</li>
</ul>
Like learning from posts like this? Subscribe for more!

Note: itemIndex is derived from the name item, to allow using indices of nested repeaters

2.2 If statement

<label rt-if="this.hasError()">{this.getError()}</label>
Like learning from posts like this? Subscribe for more!

Note: this is a true if, meaning that will not render the node at all if the expression is false.

2.3 Syntactic sugars - rt-class, rt-scope, expressions in attributes

<div rt-scope="this.getUserDetails() as theUser" title="{theUser.loginName}">
    Real Name: {theUser.firstName} {theUser.lastName}<br/>
    Login: {theUser.loginName}
    Last paid at: <span rt-class="{status:true, overdue:this.isUserOverdue(theUser)}">{theUser.lastPaid}</span>
</div>
Like learning from posts like this? Subscribe for more!

Note: We've been really careful not to create too many of these, as we wanted to keep it simple. Only the stuff that adds a lot of value has been added.

2.4 Transclusion

<div>{this.props.children}</div>
Like learning from posts like this? Subscribe for more!

Note: Really simple…

2.5 Handling events

<div>
    <div rt-repeat="task in tasks" style="font-weight:{task.selected ? 'bold' : 'normal' }" onClick="() => this.toggleTask(task)">{task.title}</div>
    <button onClick="{this.save}">Save</button>
</div>
Like learning from posts like this? Subscribe for more!

Note: This is one of the nicest things in React templates. We generate methods for you, so that you don't need to store anything on DOM or work with indices. You can just write your logic code and work with your objects. There are 2 options supported: lambda expression, or if the {} notation is used, it is an expression that should return a pointer to a function. And lastly, every custom attribute for custom control that starts with on and a camelCase event name can work with both notations.

2.5 Loading resources for the templates

<rt-require dependency="./utils/translate" as="tr"/>
<rt-require dependency="./comps/colorPicker" as="colorPicker"/>
<form>
    {tr('Enter_Your_Name')}: <input type="text" valueLink="{this.linkState('name')}"/><br/>
    {tr('Choose_Favorite_Color')}: <colorPicker valueLink="{this.linkState('favColor')}"/>
</form>
Like learning from posts like this? Subscribe for more!

2.6 Other goodies

The style attribute (just) works as in html. This means that there is no need to translate the keys to camelCase (as required by React), and you can, like everywhere else, use the {} notation to insert an expression. "class" attribute also works (without the need to call it "className").

3. Summary

Both frameworks are awesome, and it's hard to decide which to use. Angular is very opinionated, which can be great if it fits your development scenario. React gives you freedom and simplicity, but lacks the declarative power of Angular. However, when using react-templates, you'll get to use a lot of the stuff we love about Angular, but without the messy stuff. For people that are strong in vanillajs, have complex projects, care about file packaging or want to use a framework in conjunction with other libraries, we believe that React + react-templates is a winning solution.

(转载)堪称最好的A*算法

如此好贴,不能不转!原文地址:http://dev.gameres.com/Program/Abstract/Arithmetic/AmitAStar.mht 本文版权归原作者、译者所有,我只是转贴;...
  • Changer_sun
  • Changer_sun
  • 2018年01月16日 20:31
  • 80

Angular vs React 最全面深入对比

如今,Angular和React这两个JavaScript框架可谓红的发紫,同时针对这两个框架的选择变成了当下最容易被问及或者被架构设计者考虑的问题,本文或许无法告诉你哪个框架更优秀,但尽量从更多的角...
  • powertoolsteam
  • powertoolsteam
  • 2017年05月02日 12:20
  • 2031

JavaScript 年度调查报告:React、Vue 和 Angular 三分天下,谁将在 2018 年独占鳌头?

点击上方“CSDN”,选择“置顶公众号”关键时刻,第一时间送达!要论 2017 年最主流的三个 Web 前端框架,应莫过于 Angular、Vue 和 React 了。然而在实际应用中,这三个框架却不...
  • csdnnews
  • csdnnews
  • 2017年12月28日 00:00
  • 1191

三分天下如何选择vue,angular,react

随着近几年的发展,前端已经不单单是html+css编写样式静态页了,而是往着更深层次发展,越来越多的前端js框架:angular、vue、react纷纷研发出来了。而作为前端的你。该如何选择? ...
  • m0_37516170
  • m0_37516170
  • 2017年02月19日 19:10
  • 5107

前端学习总结(二十三)——前端框架天下三分:Angular React 和 Vue的比较

前端这几年的技术发展很快,细分下来,主要可以分成四个方面:1.开发语言技术,主要是ES6&7,coffeescript,typescript等; 2.开发框架,如Angular,React,Vue....
  • haoshidai
  • haoshidai
  • 2016年08月28日 17:56
  • 61762

Angular与React的区别

Angular与React的区别
  • victoryzn
  • victoryzn
  • 2017年09月15日 08:09
  • 518

angular/vue/react优劣性对比分析

首先,我们先了解什么是MVX框架模式?MVX框架模式:MVC+MVP+MVVM1.MVC:Model(模型)+View(视图)+controller(控制器),主要是基于分层的目的,让彼此的职责分开。...
  • michaelli918
  • michaelli918
  • 2017年08月04日 16:48
  • 945

Vue,react,angular三种框架比较

1.Vue&&React Vue与react比较,相同之处在于: - 都使用了virtual DOM - 提供了响应式和组件化的视图组件 - 将注意力集中...
  • RheaWang
  • RheaWang
  • 2017年08月02日 15:31
  • 3842

Angular React 和 Vue的比较

 前端这几年的技术发展很快,细分下来,主要可以分成四个方面: 1.开发语言技术,主要是ES6&7,coffeescript,typescript等;  2.开发框架,如Angular,Rea...
  • yyem954135
  • yyem954135
  • 2017年06月14日 10:26
  • 1448

Vue.js vs React vs Angular 深度对比

这个页面无疑是最难编写的,但我们认为它也是非常重要的。或许你曾遇到了一些问题并且已经用其他的框架解决了。你来这里的目的是看看 Vue 是否有更好的解决方案。这也是我们在此想要回答的。 客观来说,...
  • English0523
  • English0523
  • 2016年12月29日 09:37
  • 3256
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Angular vs. React - the tie breaker
举报原因:
原因补充:

(最多只允许输入30个字)