Mad Dogs: Angular 2 vs React

    Meet the confrontation of two frameworks: Angular and React in a duel format on the example of a specific simple application. Evgeny Gusev ( @bunopus ) stands for Angular , Ilya Taratukhin ( @ilfa ) stands for React . To draw honest conclusions, they first switched technologies and tried to deploy a basic project. Starting on React created a lot of problems, but with Angular, things were much simpler, because this is an ideal application for a person who did not particularly work with the front-end. But, of course, this was only the beginning, then a real dispute went on , all the stages of which are under the



    cut About speakers:

    Evgeny Gusev has more than ten years of experience as a developer, and has been working for Wrike for the past few years . At first he developed in C ++ / C #, and then decided that all the movement and money on the frontend and moved there. Wrike currently does not use JavaScript, but uses Dart.

    Ilya Taratukhin has been engaged in commercial development for about seven years, and all of them are in the front line. He worked in 2GIS, wrote on native JS and already seems to be a dying Knockout . In parallel with his work at Wrike, Ilya is developing his project, in which he is actively immersed in React. For more than a year, Ilya has been using the Dart + Angular 2 bundle . The experience is really interesting

    That is, Eugene has a lot of experience with Angular, Ilya with React. To be honest, they switched technologies and tried to create a fairly simple project on these frameworks.


    Disclamer: Further, the transcript of the report of Yevgeny Gusev and Ilya Taratukhin at RIT ++ 2017, everything in question is true at the time of preparation of the report, when Angular was in version 4.2.0, and React - 15.5.0. However, the comparison covers the most significant aspects for which no significant changes have occurred, despite the fact that Angular 6.0.0-rc.3 has already been released.

    Part 1. Introducing




    The essence of the project is as follows: there is an input field into which the name of the city is driven in, by http-requests on the weather server the weather in the selected city is found out - in St. Petersburg again it is cloudy, and you have to go drink beer. Nothing complicated.

    React


    Eugene: I began my acquaintance with React, naturally, with the choice of the ideal Starterpack  - I don’t understand anything in React.

    Let's say a customer came to me and asked me to make a weather widget. To solve this problem, I started looking for something to help me make the project, and found a great site that I recommend to everyone. I go there and see this picture: 108 Starterpacks (now there are 189 of them), with 20 of them marked as minimal.



    I had a problem choosing a framework., And there were 108 problems. But I coped and chose Starterpack on Facebook .



    I must now denigrate React in every possible way and say that everything is bad, but in fact everything was fine, and even works quite well. I started by googling " how to send an HTTP request to React " and got a link to stackoverflow, where they told me that you can use fetch, axios, something else.

    Imagine, I had 1 problem, 108 problems added to it, and then 3 more.

    Ilya: I ’ll explain that Eugene is a bit aloof from JavaScript for about two years, and forgot how the HTTP request is made in JS and what you can take fetch , because It should be in all browsers. But if that, polyfill screw and it will be fine.

    Eugene: I chose axios, of course. The next thing you need for a simple “Hello world!” Application is to write a simple application.



    There is a render function, and it has a simple input, that is, everything is simple - you drive something in, and onChange does setState.



    I had to use Bind ! Okay, this is probably not a React problem - this is my problem. Another simple “Hello world!” Application needs tests.

    Briefly about tests - everything is bad


    I did not succeed in launching them the first time, I gave up and decided that Ilya was smarter, although I did not even ask him.

    Marginal notes


    Eugene: After my extensive experience in React, I want to clarify the following: how to combine component names and class names according to styleguide? Ilya, what do you call your components in React?

    Ilya: Since the component is a certain class, I call it CamelCase with a capital letter.

    Eugene: Everything inside me turns upside down, because the markup should be with a small letter and through hyphens. When the JSX markup classes are capitalized - CamelCase, I just feel bad.

    Secondly, I want Dependency Injection. Is there React DI in React?

    Ilya: No in React itself, but there are various tools that implement DI in full or in some kind of stripped-down version.

    Evgeny:There are probably 100 of them? But nonetheless:

    • Articles read: 4 (except docks).
    • Modules connected: 3.
    • And it's still without Redux!

    Estimate what it would turn into if I screwed Redux, Flux and other "aks" there.

    Total : 4 out of 5.



    Why 4, not 5? Yes, in Starterpack, in principle, everything is clear, but I imagine that I need to make a normal large working application sooner or later from this Starterpack. I think then I will have to read not 4 articles, but probably 104, and make my ideal Starterpack.



    Ilya: Let's move on to my experience. When you deal with Angular, everything is simpler, because there is such a colossus as Google that dictates what to do, and I very quickly came across the Angular CLI QuickStart .

    As a result, I executed 4 commands in the console.



    I’m a front-end developer - I have Node.js and NPM - there is no such problem. As a result i in 10 minutes I got a working application with hot-reload and bolted tests. Everything is cool, a lot of things have been added - I did not even immediately understand what I now have.

    The next task is the same: make an HTTP request, and before that you need to make a component that will display the result. I found that Angular Scaffolding allows you to do this in  one line , called this command and got 4 files:

    • template file;
    • style file;
    • component file;
    • the tests that arrived as a bonus are the skeleton and the first test that checks that the component is alive and it is initializing.



    Eugene: I want to say that React in the Starterpack from Facebook also has tests, but for some reason they didn’t work for me.

    Ilya The next step is to make an HTTP request. I somehow broke through the Angular documentation, found an example, almost completely copied it, and called the getWeather function.



    And I received nothing, I looked at console.log, the network tab - nothing, nothing!

    Eugene: For those who write little or don't write on Angular, Observable on RxJS is very lazy. Until you subscribe to them, they will not work.

    Ilya: I guessed that something was wrong, but I was not ready to insert this template somewhere. I just wanted to check that my HTTP request through the HTTP library that Angular provided provided works in general. So I rummaged more in the documentation and found how to do it on  Promise .



    So, I did it, called it - it all worked. In general, I was satisfied .

    The next problem. I hang up a handler, write in TypeScript in 2017, and I still need to bind the context, it shocked me a little, because I'm used to the joys of Dart.



    This is where my problems ended. I got a working application, but I still have a couple of questions.

    Open questions


    • How to get control over the assembly?

    The weather application is very simple to make, it has gathered almost out of the box. But when we start to make a serious project, we need control over the assembly. Now the whole assembly is hidden inside the cli-starter-kit.

    Eugene: Inside the Angular CLI, there is a ng eject command that removes all unnecessary starter dependencies and allows you to make everything you need from a starter application.

    • How to connect less / sass / postcss?

    Ilya: Next item. As you saw, the starter-kit generated CSS files for me, but I already want to use less, sass, stylus, postcss. I turned to Eugene: “How so? I want less! ”, But he advised just to rename the file, and indeed, the assembly automatically picked up the less file. Once again I was horrified - how much Angular pulls with itself, but it works.

    Total:


    My conclusion is that Angular is just the perfect application for a person who did not particularly work with the frontend , for someone who, for example, came from .net. He is familiar with DI, all sorts of complex abstractions, in Angular 4 you can inherit components from each other.

    But  you need to be prepared to learn the framework tools  - you will have to read a lot. This is really a huge amount of documentation. If Eugene is afraid that he will have to seriously search the Internet to work with React, then everything is collected in one place, you just need to read and understand.

    Part 2. Dispute


    Total - we met with 2 frameworks. What is our argument?

    $$$ Super Project $$$


    We made a shawarma site (or shawarma). We have a small landing page with several tabs. One of them is comments, we can understand how the state works, how something is saved, etc. The last tab is a block of contacts with the map (map as an external JS library). We will return to the map a little later - this is a pain point.

    We made a simple application for which you can get 10,000 rubles or 5 free portions of shaverma.

    Let's see Data-Flow - how flows flow in our frameworks. Let's start with Angular



    Angular (left)


    It all starts with state. In our case, this is just an ordinary array of comments, from which we take comments, somehow render them or add them.

    We put this state into our components via @ - all Angular people love dogs and square brackets. Through square brackets in the markup, write that state (comments) will be put in this comments-widget.

    If I want to add something from the widget there, and if I'm not afraid of harm, I will just do an Object Change. But it’s better not to do that.

    It is better to write @outputparentheses - these are not events, these are streams from RxJS - so they do not pop up, but work a little differently.

    React (right)


    React also has state. React generally recommends using the Flux architecture, for which there are many different tools. We pass pieces of state to the component through so-called props. I did not find the correct way to translate this word into Russian.

    Eugene: Maybe you can translate props, like things - "you are this. Pieces."

    In props, we throw data - in the component comments will be available through the comments property. When we want to handle some kind of event, for example, a click or an addition, we also send it to the props component, but it will just be a callback.

    Angular


    When we have not just comments that need to be rendered, but something huge, big, and a bunch of components, of course, it's pretty silly to do input-output. But when these are small components, for example, inside the big comments-widget there is an avatar or something else, also through input-output and square brackets you can get the data back and forth.

    React


    Nothing new at all, everything is exactly the same - we pass props to the child components, somewhere inside the CommentsWidget we sorted out the comments, and inside the comment component we pass a specific comment. Also with CommentForm we can listen to the add event and somehow handle it.

    Eugene: Of course, if we have a really large application, then it is stupid to do so. You will have a huge tree of these input-output. But we have a Dependency Injection in Angular! Is there a React DI?



    Ilya: If someone is not in the know, I didn’t know before working with Angular either - you can very unobviously set up the connections between your services and components, it’s all confusing, and just shoot yourself in the foot with each refactoring.

    Eugene: Angular is not for dumb people.

    We take a service - this is essentially just a class with a certain annotation. We shove it wherever possible - but I didn’t tell you that! In general, you only shove it where you need it - in this case, in our comments-widget.

    And where it is not needed, we use the same input-output. That is, it is a kind of hybrid system. In the comments-widget we use service calls, getting objects - everything is as usual.

    Ilya: In React, there are some stripped-down DI variants that allow, for example, to scroll some data from top to bottom.

    I will use Redux as an example, simply because it is the most popular library. Other tools work in a similar way.

    We have a store. Using the magic connect function, we connect the store to our top-level component. The top-level component knows that there is a store, where the data comes from in a certain format, and by a certain communication format through action, it can notify the store that something has happened.



    Thus, we have 2 types of components:

    1. Some smart components that are aware of the existence of state receive information about its update and notify state that they need to be updated.
    2. Contextually independent components that we can use, wherever we want, just throw the necessary props into their input.

    Eugene: And in Angular, all components are smart.

    Component definition


    Let's now look at the code and how we create components in our two frameworks.



    Angular


    In Angular, a component is a simple regular JSX, TypeScript, or Dart class - but it is a class with some slight annotation via @. You can write through selector: "Angular, look, if you see such a class, property or tag in the markup, then this is a component, treat it as a component accordingly."

    Ilya: Let me remind you that we have a dispute. Therefore, I will be as oppositional as possible.

    React


    So, in React, we describe the so-called functional setState component. We just have a function that takes a props object as input and returns a JSX template.



    Eugene: Templates in Angular are simple, plain, understandable HTML.

    Ilya: Very clear! See: ngFor, square brackets, comments, parentheses, onADD - plain HTML!

    Eugene: Yes, of course, you need to learn something - asterisks, brackets, dogs. But they say that Angular is like that because it was written by javists, it has a lot of keywords, but in general it is plain HTML.

    React


    Ilya: I’ll be honest and I’ll say that React is not quite ordinary HTML. Here in JSX there is a cross between HTML and JS code, or TypeScript code - depending on what you write. Yes, there is such a nuance, but it’s enough to take care of yourself, write in the component file only the code that relates to the display of the component. And all the heavy logic must be pulled out in the reducer, in the store, in the helper away from the component, and then everything will be clean and transparent.

    If you share developers and layout designers in your company at JS, then layout designers will quickly get used to such a description of components and will not experience problems with this.



    Angular


    Eugene: How does DI work in Angular? In fact, you just use magic and say:

    - Look, I have such and such a service in the constructor (commentsService in this case).

    And that's it, Angular will implement it for you when you have the component created. Then you just use instance during lifecycle hooks, as in this case ngOnInit. You can talk about DI until the end of the day - it's just magic.

    React


    Ilya: I'll show you some React magic. To associate a component with a store, we take the component and the connect function from Redux and pass the rules to connect. One rule will talk about how to split the Redux tree into subtrees and pass it to the component with props, and the second, on the contrary, will talk about how to wrap action Redux in callback and pass it to the component's props, that's all.

    Eugene: You, of course, forgive me, but if in the case of Angular this is magic, then this export default connect is some kind of black magic.

    Ilya: You know, in 2 years JS has changed a bit and now export default is normal.

    User interaction


    Eugene: In general, this is the most interesting part - how everything is rendered and where it breaks when the user does something.



    Angular


    We have an application, inside it comments-widget, inside it a small comment-form. These are all components. What happens when a user clicks submit somewhere in the bottom component?

    All Angular lovers love the zones. Zones are such a tricky thing that came out, oddly enough, of Dart. Zones implement monkey patch for all asynchronous functions of your browser: setTimeout, setInterval, as well as all user interactions, such as clicks.

    When something happens, the zones twitch and pull a certain code - this is ChangeDetection. ChangeDetection runs from the root for all components, determines that something has changed, and renders everything. If, for example, there were 5 comments and the 6th was added, then all 5 comments will be redirected. That's right, but very fast.

    React


    Ilya: Let's make the same React application. As we found out, it’s not a problem to make applications with plus or minus the same architecture, but it’s in the details.



    We will catch the submit event of the form, notify the component above, throw the action in the store, process the action. Store will throw emit change. Emit change will arrive to all the components that are associated with the store, and the components will begin to check the props on the topic whether the links to the store trees have changed or not.



    If they have changed, the component will call the rerender function, completely re-render the Virtual DOM, then Virtual DOM will compare its previous state with the current, with the new one, and make changes in the DOM tree pointwise.

    Eugene: Wait. We have a Virtual DOM, and in principle, potentially I have 2 copies of the entire DOM tree in my memory.

    Ilya: Is this a problem?

    Eugene: And if I have a gigabyte of memory on a laptop?

    Ilya: Laptop from 2007? But if in essence, then we have very unpleasant limitations of the real DOM. It does not allow you to keep more than 5-10 thousand DOM nodes and begins to behave inappropriately, slow down. Therefore, we cannot create many Virtual DOM nodes.

    Eugene: Especially in IE.


    Part 3. Pain


    It usually hurts after an argument.



    Angular


    What is the pain in Angular? I just didn’t tell you this, but it’s a little slow, though only if you don’t know how to cook it.



    For example, I have textarea. I want to do something on mousmove, like hanging a class or highlighting something. Then I just subscribe to mousmove and do it. Everything is simple.

    I colorize the components when the ChangeDetection occurs, and I see something like this.



    It is generally claimed that ChangeDetection is very fast. But if you have a lot of DOM nodes and components, then everything is not very fast.

    This is very easy to fix - sign up for mousmove outside the zone so that Angular does not bother you. Then, when you need something, you can return back to the zone.



    Ilya: We create a zone so that everything works cool automatically, and then we try to get around this !?

    Eugene: So it is! I said that Angular is not for dumb.

    That would be all true if not for Angular-4. The guys tried, did everything well. In general, Angular is really fast, beautiful, and works great.



    React


    Ilya: A bit about the pain of React. At one time, when I started immersing myself in React, I decided that I would now write applications on a framework that works through state. It seems to be simple, right? And then you think: “I would now put a classic on the DOM node, I would work out some kind of animation, and then I would remove this classic!” But no, such things do not work in React.



    When you write an application in React, the first couple of months you learn to rebuild your thinking and write an application in React - change state and understand how your application will change after it changes. One way or another, everyone who is completely immersed in React learns this and understands how to work with it.

    In the sample application, there was a block with a map. If you need to insert a third-party card, there may be two options.

    Good outcome. Some guys, for example, from 2GIS wrote their React-wrapper over the library. Map - a certain third-party JS application that builds a DOM tree can be a simple component. You use it and that’s it.



    Another option . But sometimes you want to connect a JS library that no one connected or connected to you in React before, but did not post in the open source solution how to wrap a JS library in a React component. And the adventure begins.



    You will learn that React has a lot of lifecycle hooks, some of which you will have to use. First you need to use componentDidMount, wait until your React component is rendered and inserted into the DOM. Then you can initialize this third-party JS library, pass the DOM node to it, and there it will deploy its belongings.

    You need to remember the lifecycle hooks in componentWillReceiveProps, and each time you update the props at the input of the component, you need to write a huge logic with your hands, which, when this property is changed, will understand what needs to be done in the language of calling the functions of this library.

    In my example, it's simple, but I suspect there will be a huge footcloth.

    You will need to remember lifecycle hooks shouldComponentUpdate. Here we just return false and say: “React, we gave you a gif in the render, consider it empty, and don’t get into it at all”

    One more thing


    Eugene: Let's talk a bit about tools.

    Angular


    Angular, of course, has it all. You do not need anything, thank you all.
    • Angular-CLI  is a great thing, I recommend everyone to use it.
    • Если нужны дополнительные инструменты, есть Augury, который помогает отлаживать приложения на Angular. Там показаны компоненты, роуты и все прочее. Тоже рекомендую.
    • Ngrev — штука от небезызвестного Минко Гечева, которая использует статический анализ кода и анализирует Angular-приложения на предмет связи и всего прочего. Тоже рекомендую посмотреть.

    React


    Ilya: React can be loved at least for the excellent DevTools.



    There is React DevTools, which helps to present the application not as a DOM tree, but as React components; see which component is embedded in which; see the magic wrapper components that Redux creates, for example, and which props came to the input of the component; understand where and what was done wrong.

    It seems to me that many started using React when they saw DevTools. These tools allow you to travel in time and see the history of the state change, rewinding the state of the application a few steps back.

    Eugene: Return to 2007?

    Ilya: If the tab lived for a very long time, then why not?



    Also there are useful goodies: diff between the nearest states, a full state and a test tab, in which moki are generated for testing. You can take mokas based on the current state of the application, cram into state and tests that will check something. There will be no need to take steps that will translate the application to the desired state, state will simply create the application, and then you will check whether everything is fine when the application is in this state.

    Part 4. The End


    After an argument, there is pain, and after pain, it’s the end. To summarize some of the Angular vs. React battle.



    Angular


    • Syntax. Angular is a great and clear syntax. This is HTML, it works, and you don’t need to learn weird JSX, just some stars, brackets and more. I don’t see anything wrong with that.
    • Языки. На Angular можно писать на JavaScript, на TypeScript, на Dart, на Flow — на чем хотите.
    • Single maintainer. У Google есть Angular, у Angular есть Google — со всеми минусами и плюсами. Из плюсов — если обновляется Angular, я могу точно утверждать, что работают все остальные пакеты, которые входят в Angular, но, с другой стороны, все знают, что Google есть Google.
    • Коробочное решение. Вы можете быть уверены, что если вы сделаете CLI install, то у вас будет все, что нужно — HTTP запросы, тесты и т.д. Причем все из коробки и все работает. В принципе, кое-что можно заменять, но большинство людей использует уже готовое со всеми плюсами и минусами.

    React


    • Синтаксис. У React — это конечно JSX. Нет, вы можете писать без JSX, но я не видел людей, которые так делают. К JSX довольно быстро привыкаешь и понимаешь, насколько это удобно.
    • Языки. В случае с React самым популярным языком пока остается JS. Сейчас есть небольшое движение в сторону TypeScript, есть гики, которые пишут на Dart, но это совсем не мейнстрим.
    • Community. У React есть Facebook, который выпускает новые версии React, делает совершенно новый продукт React Fiber, у которого будет такой же интерфейс, но совершенно другие внутренности. Но у Reactа очень большое community, и вы с большой вероятностью сможете собрать приложение из готовых компонентов, подключить обернутые привычные библиотеки и это использовать.
    • Constructor . React is just a template engine that recommends using the Flux approach, and then you either collect the entire ecosystem from pieces yourself, or simply take the finished Starter-pack that you like and drags a lot of dependencies.



    At the conference, Eugene and Ilya voted Angular vs React right in the course of the report, but, unfortunately, bots joined the game. Therefore, let's repeat in the survey for this article.

    Обещаем, что и в этом году на фестивале РИТ++ скучать не придется — пул докладов по фронтенду очень серьезный. Вот несколько примеров:

    Андрей Солодовников (N1.RU) обещает помочь разобраться, подходит ли Vue.js для создания большого web-приложения, рассказать, что делает разработку на Vue.js реально удобной и как обстоят дела с производительностью.

    Виталий Глибин из Хантфлоу не утверждает, что будет легко объяснить бизнесу, почему вам нужно полгода, чтобы все переписать с нуля на этом модном и современном фреймворке. Но
    предлагает поделиться личным опытом миграции большого и сложного приложения с Backbone на Vue, и рассказать о том, почему удалось сделать это без вреда для бизнеса (а даже наоборот).

    Юрий Юрин предлагает сэкономить вам более 100 часов, которые в Skyeng потратили на обсуждения, эксперименты и код, попытавшись научиться на чужих ошибках. Доклад "Техническая сторона создания UI-kit на Angular 4/5" будет посвящен процессу вынесения общего кода в библиотеку.

    В докладе Михаила Башурова из Luxoft речь пойдет об event loop, рассмотрим, что это такое и с чем его едят. Поговорим, как пользоваться asynchronous J ava S cript , which has one stream at the same time, and does not shoot itself in the leg.

    In total , about 60 applications have been submitted  to  Frontend Conf , but less than half will be selected. Follow the news, and you can book tickets without waiting for the exact program.

    Only registered users can participate in the survey. Please come in.

    Angular vs React

    • 47.9% Angular 271
    • 52% React 294

    Also popular now: