E agora, Angular ou React?

Post Original

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:

To see full unobfuscated code samples

Whereas in Angular it will look like:

To see full unobfuscated code samples

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

<u{}{} <li="" rt{}{}ep{}{}t="{}{}tem" in="" it{}{}s"{}{}it{}{}}="" at="" in{}{}x="" {i{}{}mi{}{}ex{}{}="" l{}{}="" <="" {}{}="">

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>

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

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

 

Anúncios

Deixe um comentário

Preencha os seus dados abaixo ou clique em um ícone para log in:

Logotipo do WordPress.com

Você está comentando utilizando sua conta WordPress.com. Sair / Alterar )

Imagem do Twitter

Você está comentando utilizando sua conta Twitter. Sair / Alterar )

Foto do Facebook

Você está comentando utilizando sua conta Facebook. Sair / Alterar )

Foto do Google+

Você está comentando utilizando sua conta Google+. Sair / Alterar )

Conectando a %s