Angular vs. React - the tie breaker

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
东南亚位于我国倡导推进的“一带一路”海陆交汇地带,作为当今全球发展最为迅速的地区之一,近年来区域内生产总值实现了显著且稳定的增长。根据东盟主要经济体公布的最新数据,印度尼西亚2023年国内生产总值(GDP)增长5.05%;越南2023年经济增长5.05%;马来西亚2023年经济增速为3.7%;泰国2023年经济增长1.9%;新加坡2023年经济增长1.1%;柬埔寨2023年经济增速预计为5.6%。 东盟国家在“一带一路”沿线国家中的总体GDP经济规模、贸易总额与国外直接投资均为最大,因此有着举足轻重的地位和作用。当前,东盟与中国已互相成为双方最大的交易伙伴。中国-东盟贸易总额已从2013年的443亿元增长至 2023年合计超逾6.4万亿元,占中国外贸总值的15.4%。在过去20余年中,东盟国家不断在全球多变的格局里面临挑战并寻求机遇。2023东盟国家主要经济体受到国内消费、国外投资、货币政策、旅游业复苏、和大宗商品出口价企稳等方面的提振,经济显现出稳步增长态势和强韧性的潜能。 本调研报告旨在深度挖掘东南亚市场的增长潜力与发展机会,分析东南亚市场竞争态势、销售模式、客户偏好、整体市场营商环境,为国内企业出海开展业务提供客观参考意见。 本文核心内容: 市场空间:全球行业市场空间、东南亚市场发展空间。 竞争态势:全球份额,东南亚市场企业份额。 销售模式:东南亚市场销售模式、本地代理商 客户情况:东南亚本地客户及偏好分析 营商环境:东南亚营商环境分析 本文纳入的企业包括国外及印尼本土企业,以及相关上下游企业等,部分名单 QYResearch是全球知名的大型咨询公司,行业涵盖各高科技行业产业链细分市场,横跨如半导体产业链(半导体设备及零部件、半导体材料、集成电路、制造、封测、分立器件、传感器、光电器件)、光伏产业链(设备、硅料/硅片、电池片、组件、辅料支架、逆变器、电站终端)、新能源汽车产业链(动力电池及材料、电驱电控、汽车半导体/电子、整车、充电桩)、通信产业链(通信系统设备、终端设备、电子元器件、射频前端、光模块、4G/5G/6G、宽带、IoT、数字经济、AI)、先进材料产业链(金属材料、高分子材料、陶瓷材料、纳米材料等)、机械制造产业链(数控机床、工程机械、电气机械、3C自动化、工业机器人、激光、工控、无人机)、食品药品、医疗器械、农业等。邮箱:market@qyresearch.com

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值