Angular vs React: який вибрати для свого додатка

Точне паралельне порівняння загальних та технічних аспектів Angular та React

Є так багато статей під назвою “Angular vs React”, “React vs Angular”, “Angular or React” - це диво, що ви відкрили цю! Однак цих статей не вистачає - це точне пліч-о-пліч порівняння Angular vs React.

Отже, це те, що я збираюся зробити в цій публікації в блозі: розмістити React та Angular у прямому зіставленні. Ми розглянемо та порівняємо два фреймворки JavaScript і розглянемо кожну можливу характеристику, щоб переконатися, що не пропустимо жодної частини даних.

Зрештою, я не збираюся казати вам, яку технологію вибрати. Але я дам вам достатньо їжі для роздумів, щоб ви могли вибрати технологію, яка найбільше підходить вам і вашому проекту.

пошук (1)

1. Короткий огляд

Зреагуйте

React - це бібліотека JavaScript для розробки інтерфейсу користувача. Ним керує Facebook та спільнота розробників з відкритим кодом.

Структура була введена в травні 2013 року.

Останні оновлення були опубліковані 8 серпня 2019 року - трохи більше місяця тому.

Кутовий

Angular - це фреймворк JavaScript з відкритим кодом для веб- і мобільних розробок. Він заснований на TypeScript і управляється командою Google Angular та спільнотою розробників Angular.

Випущений у вересні 2016 року, Angular (також відомий як Angular 2.0) - це повний рерайт AngularJS (Angular 1.0), який був представлений в 2010 році.

Вже існує шість версій Angular, а останній реліз відбувся 28 серпня 2019 року - майже три тижні тому.

Інтернет (1)

2. Універсальність

Зреагуйте

React - це фреймворк, який використовується як в Інтернеті, так і в мобільній розробці. Однак для розвитку мобільних пристроїв її потрібно інтегрувати в Кордову. Більше того, для мобільної розробки існує додатковий фреймворк - React Native.

React можна використовувати для створення як односторінкових, так і багатосторінкових веб-додатків.

Кутовий

Angular підходить як для веб, так і для мобільних розробок. Однак у розробці мобільних пристроїв велику частку роботи виконує Ionic. Крім того, подібно до React, Angular має додаткову мобільну структуру розробки. Аналогом React Native є NativeScript.

Angular також можна використовувати як для одно-, так і для багатосторінкових веб-програм.

успіх (1)

3. Самодостатність

Зреагуйте

React - це основа для розробки інтерфейсу користувача, тому для програм, написаних за допомогою React, потрібні додаткові бібліотеки. Наприклад, Redux, React Router або Helmet оптимізують процеси управління станом, маршрутизації та взаємодії з API. Такі функції, як прив'язка даних, маршрутизація на основі компонентів, генерація проекту, перевірка форми або введення залежностей вимагають встановлення додаткових модулів або бібліотек.

Кутовий

Angular - це повноцінна структура для розробки програмного забезпечення, яка, як правило, не потребує додаткових бібліотек. Всі вищезазначені функції - прив'язка даних, маршрутизація на основі компонентів, генерація проекту, перевірка форми та введення залежностей - можуть бути реалізовані за допомогою пакета Angular.

відкрита книга

4. Крива навчання

Зреагуйте

React мінімалістичний: без введення залежностей, без класичних шаблонів, без надто складних функцій. Зрозуміти структуру буде досить просто, якщо ви вже добре знаєте JavaScript.

Однак потрібно досить багато часу, щоб навчитися створювати проект, оскільки відсутня заздалегідь визначена структура проекту. Вам також потрібно вивчити бібліотеку Redux, яка використовується в більш ніж половині програм React для управління станом. Постійне оновлення фреймворку також вимагає додаткових зусиль від розробника. Крім того, у React є досить багато найкращих практик, яких вам потрібно буде навчитися робити все правильно.

Кутовий

Angular сам по собі є величезною бібліотекою, і вивчення всіх пов'язаних з ним концепцій займе набагато більше часу, ніж у випадку з React. Angular складніше зрозуміти, є багато непотрібного синтаксису, а управління компонентами є складним. Деякі складні функції вбудовані в основу фреймворку, а це означає, що розробник не може уникнути їх вивчення та використання. Більше того, існує безліч способів вирішення одного питання.

Незважаючи на те, що TypeScript дуже нагадує JavaScript, для вивчення потрібно також деякий час. Оскільки фреймворк постійно оновлюється, розробнику потрібно докласти додаткових зусиль для навчання.

користувачі (1)

5. Громада

Зреагуйте

Фреймворк React є одним з найпопулярніших фреймворків JS у всьому світі, і спільнота, що підтримує та розробляє його, величезна.

Working with React, you have to be a continuous learner since the framework is often updated. While the community tries to go forward with the latest documentation as swiftly as possible, keeping up with all the changes is not that easy. Sometimes, there may be a lack of documentation, but the issue is often solved by the community support on thematic forums.

React is actively used by such companies as Facebook, Twitter, Netflix, Airbnb, PayPal, The New York Times, Yahoo, Walmart, Uber, and Microsoft.

Angular

Angular is less admired than React and faces a lot of skepticism, partially because of the unpopularity of Angular 1.0. Developers used to dismiss the framework as an overly complicated one as it required a lot of time to be spent learning. However, this framework has been developed by Google, which works in favor of Angular’s credibility.

Google provides the long-term support of the framework and constantly improves it. However, the updates are so fast that the documentation often falls behind.

Angular is used by such companies as McDonald’s, AT&T, HBO, Apple, Forbes, Adobe, Nike, and Microsoft as well.

налаштування (1)

6. Performance

React

React’s performance is greatly improved with the introduction of the virtual DOM. Since all virtual DOM trees are lightweight and built on server, the load on browser is reduced. Furthermore, since the data-binding process is unidirectional, bindings are not assigned watchers as in the case of Angular. Respectively, no additional workload is created.

Angular

Angular performs worse, especially in the case of complex and dynamic web apps.

The performance of Angular apps is negatively affected by bidirectional data-binding. Each binding is assigned a watcher to track changes, and each loop continues until all the watchers and associated values are checked. Because of this, the more bindings you have, the more watchers are created, and the more cumbersome the process becomes.

However, the most recent update of Angular has greatly improved its performance, and it does not lose to React anymore. Moreover, the size of an Angular application is slightly smaller than the size of a React app.

меню (1)

7. Language

React

React is based on JavaScript ES6+ combined with JSX script. JSX is an extension for syntax, which makes a JavaScript code resemble that written in HTML. This makes the code easier to understand, and typos are easier to spot. For the JSX code to be compiled in a browser, React is augmented with Babel – a code translation tool.

Angular

Angular can use JavaScript or TypeScript, which is a superset of JS developed specifically for larger projects. TypeScript is more compact than JavaScript, the code is easier to navigate, and typos are easily spotted. Code refactoring process also becomes simpler and faster.

шари (2)

8. App Structure

React

The structure of React provides developers with the freedom to choose. There is no “the only right structure” for a React app. However, the necessity to design the app structure at the beginning of each project makes it more difficult and longer to start.

Besides, React offers only View layer, while Model and Controller are added with the usage of other libraries.

The architecture of a React app is component-based. The code is made of React components, which are rendered with React DOM library and directed in two ways: functional (with a function that returns JSX)...

function Hello(props){ return Hello {props.name} }

...and class-based (with ES6 classes).

class Hello extends React.Component { render() { return 

Hello, {this.props.name}

; }

Angular

The structure of Angular is fixed and complex, suitable for experienced developers.

Angular is based on three layers – Model, Controller, and View. An object responsible for the Model is initialized by the Controller and displayed with the View.

The application code consists of different Angular components, each being written in four separate files: a TypeScript to implement the component, an HTML file to define the view, a CSS file to define the stylistic features, and a special file for testing purposes. Links to these files are written in the app directive, which displays the structural logic of the app. Respectively, Angular components are also reusable.

import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { }
додаток (1)

9. UI Components

React

UI tools for React are developed by the community. There are a lot of free and paid UI components on the React portal. To use material design components in React, you would have to install an additional library – Material-UI Library & Dependencies.

Angular

Angular has a built-in Material toolset, and it offers a variety of pre-built material design components. There are various buttons, layouts, indicators, pop-ups, and form controls. Because of this, UI configuration becomes simpler and faster.

файл (1)

10. Directives

React

In React, templates and logic are explained in one place – at the end of the component. It allows the reader to quickly grasp the meaning of the code even if they do not know the syntax.

Angular

In Angular, each template is returned with an attribute – a directive of how the object has to be set. The syntax of Angular directives is complex and sophisticated, which makes it incomprehensible for a reader without any experience in working with this technology.

елементи керування (1)

11. State Management

React

In React, each component has its own state. A React developer can create special components for holding the state of the entire application or a particular part of it. The major disadvantage here consists in the fact that the global state needs to be stored in multiple different parts of the app with data being manually passed around different component tree levels.

class Clock extends React.Component { constructor(props) { super(props); this.state = {date: new Date()}; } render() { return ( 

Hello world!

Now is {this.state.date.toLocaleTimeString()}.

); } }

To solve this problem, there is a special state management library – Redux. The idea of it is that the global state is represented as a single stateful object, which is altered in different parts of the app with the help of reducers – special Redux functions.

Another solution is offered by the state management library MobX. Unlike Redux with the global state stored in a single immutable stateful object, MobX offers storing only the minimal required state, while the rest of it can be derived.

Angular

In Angular, component data is stored in component properties. Parent components pass data through to children ones. State changes in some parts can be identified and recalculated, but in a large app, it can cause a multi-directional tree series of updates, which will be difficult to track. The features can be improved with the help of state management libraries, such as NgRx or RxJS , which would make sure that the data flow is unidirectional.

export class HeroListComponent implements OnInit { heroes: Hero[]; selectedHero: Hero; constructor(private service: HeroService) { } ngOnInit() { this.heroes = this.service.getHeroes(); } selectHero(hero: Hero) { this.selectedHero = hero; } } 
мережа (1)

12. Dependency Injection

React

React does not fully support dependency injection as it does not fully comply with the idea of functional programming and data immutability. Instead, it has a global state for all components.

Angular

The greatest advantage of Angular rests in the fact that, unlike React, it supports dependency injection. Therefore, Angular allows having different lifecycles for different stores.

import { Injectable } from '@angular/core'; import { HEROES } from './mock-heroes'; @Injectable({ // we declare that this service should be created // by the root application injector. providedIn: 'root', }) export class HeroService { getHeroes() { return HEROES; } }
від'єднати (1)

13. Data Binding

React

Data binding stands for the data synchronization process between Model and View. React should be augmented with Redux, which allows you to work with immutable data and makes data flow unidirectional. Unidirectional binding is predictable, which facilitates the debugging process.

Angular

Angular works with bidirectional data-binding and mutable data. While the advantages of mutable and immutable data are a matter of a heated discussion, it is definitely easier to work with bidirectional data-binding rather than with the unidirectional approach. At the same time, bidirectional data-binding negatively affects the performance since Angular automatically develops a watcher for each binding.

The ways of data-binding in Angular:

{{expression}} Interpolation [target]="expression" Property bind-target="expression" Attribute
(target)="statement" Event on-target="statement" Event
[(target)]="expression" Two-way bindon-target="expression" Two-way
перетасувати (1)

14. Change Rendering

React

React uses a virtual Document Object Model (DOM), which enables easily implementing minor data changes in one element without updating the structure of the entire tree. The framework creates an in-memory cache of data structure, computes the changes, and efficiently updates the DOM displayed in the browser. This way, the entire page seems to be rendered on each change, whereas actually, the libraries render changed subcomponents only.

The React team is constantly improving Fiber – a mechanism aimed at boosting the productivity of change rendering.

Angular

Angular uses a real DOM, which updates the entire tree structure even when the changes have taken place in a single element. The real DOM is considered to be slower and less effective than the virtual DOM.

To compensate for this disadvantage, Angular uses change detection to identify components that need to be altered. Therefore, the real DOM on Angular performs as effectively as the virtual DOM on React.

редагувати (1)

15. Tools

React

React is supported by multiple code editors. For instance, the code in React can be edited with Sublime Text, Visual Studio, and Atom. To bootstrap a project, you can use the Create React App (CLI) tool. In turn, server-side rendering is completed with the use of Next.js framework.

To test the entire app written in React, you would need multiple tools. For instance, Enzyme for component testing, Jest for testing JS code, React-unit for unit testing and so on. To debug the app in the development mode, you can use a browser extension React Dev Tools.

Another interesting tool is React 360, which is a library used for creating AR and VR applications.

Angular

Similarly to React, Angular is supported by a variety of code editing tools. For example, you may work with such code editors as Aptana, Sublime Text, and Visual Studio. A project can be promptly set up with Angular CLI. Server-side rendering is completed with the help of Angular Universal.

Unlike React, Angular can be fully tested with a single tool. For the end-to-end testing in Angular, the platforms are Jasmine, Protractor, and Karma. Another tool that debugs the app in the development mode is a browser extension Augury.

To Wrap Up

Angular is a full-fledged mobile and web development framework. React is a framework only for UI development, which can be turned into a full-fledged solution with the help of additional libraries.

React seems simpler at first sight, and it takes less time to start working on a React project. However, that simplicity as the main advantage of React is neutralized because you have to learn to work with additional JavaScript frameworks and tools.

Angular itself is more complex and takes quite some time to master. Yet, it is a powerful tool that offers a holistic web development experience, and once you learn how to work with it, you reap the fruits.

There is no better framework. Both are updated continuously to keep up with the competitor. For instance, while React was believed to win because of its virtual DOM, Angular equaled the score by implementing change detection. While Angular was considered to be winning because of being developed by such an authoritative company as Google, the immense devoted React community fully compensated for Google's reputation and made React similar to Angular.

In the end, React vs Angular is all a matter of personal preference, a matter of skills and habits. As a beginner in programming, you would probably benefit more from starting with React. As an experienced developer, you just keep working with what you know better.

Do not forget to challenge yourself and start learning a new framework, React or Angular. As a Project Manager or a business owner outsourcing developers, you should talk to your web development team and together choose the framework that suits all of you best, whether it be Angular or React.

Do you have an idea for either an Angular or React project?

My company KeenEthics is experienced in react development, and we, also, provide outstanding agularjs developers for your projects. In case you need the following services, feel free to get in touch.

If you have enjoyed the article, you should definitely read another wonderful comparison of 2 JS frameworks: React vs Svelte: How to Build Messaging Components.

P.S.

Я хотів би подякувати усім, хто долучився до цієї статті, зокрема Сергію Горностаєву та Володі Андрущаку, розробникам програмного забезпечення @ KeenEthics.

Оригінальну статтю, розміщену в блозі KeenEthics, можна знайти тут: Angular vs React: Який вибрати для свого додатка.