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.

相关文章推荐

Vue.js vs React vs Angular 深度对比

这个页面无疑是最难编写的,但我们认为它也是非常重要的。或许你曾遇到了一些问题并且已经用其他的框架解决了。你来这里的目的是看看 Vue 是否有更好的解决方案。这也是我们在此想要回答的。 客观来说,作为...

如何选择前端框架:ANGULAR VS EMBER VS REACT

最近一段时间是令前端工程师们非常兴奋的时期,因为三大Web框架陆续发布新版本,让我们见识到了更强大的Web框架。Ember2.0在2个月之前已经发布,从1.0升级到2.0非常简单。几周之前React发...

Vue+React+Angular精品中午文档

  • 2017年10月29日 02:34
  • 87.21MB
  • 下载

web前端入坑第五篇:秒懂Vuejs、Angular、React原理和前端发展历史

秒懂Vuejs、Angular、React原理和前端发展历史2017-04-07 小北哥哥 前端你别闹今天来说说 “前端发展历史和框架” 「前端程序发展的历史」「 不学自知,不问自晓,古今行事,未之有...

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

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

vue.js与angular,react等框架分析…

Angular 选择 Vue 而不选择 Angular,有下面几个原因,当然不是对每个人都适合: 在 API 与设计两方面上 Vue.js 都比 Angular 简单得多,因此你可以快速地掌握...
  • aa_mmnn
  • aa_mmnn
  • 2017年03月18日 16:30
  • 761

前端框架选型续 && 分享下使用 Backbone、Vue、Angular、React 的经验

上周,知乎上有几篇关于 Angular 和 Vue 对比的文章。本来想着的是,这些文章倒是可以指导下新手,作一些技术选型。可遗憾的是,开始的文章失去了一些偏颇,后面的文章则开始了一些攻击性行为。慢慢的...
  • gmszone
  • gmszone
  • 2017年08月08日 23:34
  • 661

Vue.js 很好,但会比 Angular 或 React 更好吗?

Vue.js 是一个用来构建网页界面的 JavaScript 库。同其它的一些工具结合在一起,它也可以成为一个新“框架”。通过阅读我们最近一次在 ValueCoders 上发表的 文章, 你会了解...

Angular团队发布路线图,并演示如何与React Native集成

本文来源于我在InfoQ中文站翻译的文章,原文地址是:http://www.infoq.com/cn/news/2015/06/angular-2-react-native-roadmap前不久在旧金...

Angular-Vue-React

Angular-Vue-React
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Angular vs. React - the tie breaker
举报原因:
原因补充:

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