Read time:
10 minutes
Dominic Reynolds
In the blue corner, weighing in at zero pounds (it’s opensource); we have the favourite of 41% of web developers! It’s lightweight, nimble and fast. It’s React! Aaaaand in the red corner, also weighing in at zero pounds; we have the sturdy, secure and feature packed framework. Adopted by 17% of web developers. It’s Angular!
Angular and React hold a deep similarity in that both of them ultimately attempt to solve the same problem. However, the approach and feel of these two JavaScript frameworks are dramatically different. In this blog post, we will explore the advantages and disadvantages of both frameworks, debate the use cases for each, see some examples of how the coding style differs and learn about how they work.
For a long time, the experience of browsing the web was one of static web pages, consisting of an html template with little interactivity. The task of manipulating the DOM (Document Object Model – i.e. What you see on the web page) was possible, but very involved. This meant that when a user wanted to go to a new page within a site, an HTTP request would be sent to a server, which would then return a whole new html template for the new page.
This all changed when Google burst onto the scene in October 2010 with their new JavaScript framework, AngularJS. AngularJS allowed for front end developers to create single page applications with comparative ease. As AngularJS was not intended initially for all of the use cases that it found itself being used in. Rather than continually patching it, Google replaced it with a rewrite in 2015, (initially called Angular 2, but now just known as Angular), which requires the use of TypeScript.
In May 2013, Facebook made ReactJS open source, a framework they had developed back in 2011 in order to tackle the challenge of offering their users a more dynamic and responsive user interface. In 2018, React introduced hooks with version 16.8.0 which completely changed the way React code could be written. Previous to this release, React was always written with class based components. Hooks enabled the use of functional components; this new approach was much more performant, easier to understand and completely backwards compatible with previous versions of React. This meant that unlike Angular’s switch to Angular 2, the move to this new version of React was seamless and did not require developers to rewrite their projects in order to stay up to date.
React has little structure to its coding style, allowing for fast development, not hindered by enforced conventions and naming styles. This is the first significant difference it has with Angular, which has coding and naming conventions.
Angular is derived from the MVC (Model View Controller) model, each module has a folder, and contained within that module will be components, each of which will have their own folder containing multiple (usually 4) files. These files are the template (.html), the component (.ts), the test suite (.spec.ts) and the style sheet (.css). These files can be easily generated by using the Angular-cli with the ng generate component
command. Whereas in React, a component can be contained within a single .jsx or .tsx file, with a separate style sheet and test file if needed. Additionally in React it is possible to house multiple components within a single JavaScript file, unlike Angular.
Angular is the more structured framework and comes bundled with many features that a React project would usually require developers to add third party libraries to access, with poor choices being potentially costly. For example using a poorly documented library or abandonware with no maintainers. Angular comes bundled with routing, translation and state, features that are not included with React (state is now included with the useContext hook, however many developers choose to use external libraries such as Redux for this).
These added features in Angular are great, although they have to be learned and understood correctly. Similar issues with a lack of understanding of React can happen though, for example, a poor understanding of the useEffect hook can easily lead to memory leaks and unnecessary renders. Management of memory and unnecessary re-renders should always be thoughtfully considered when developing applications using either library, although when using Angular it is essential to be more explicit in memory management in certain cases, such as when subscribing to a service.
In React, props are used to pass state from a parent to child component. This is one way, so in order to pass state the other way, a state management library is required as React components cannot access their children. Angular has two way state management, state can be passed down from parent to child component through inputs, and it can be passed the other way from child to parent through outputs, Angular components can also directly access their children through the @viewChild
decorator. This is certainly an advantage Angular has over React.
Angular’s built in state management with services and subscriptions does take some time to learn to use correctly, but when implemented well, it can be very powerful and allows for the management of state at a level of scope that the developer has complete control over. React’s built in useContext hook can be used for this purpose too, although the more complete scope of Angular’s state management is certainly more powerful.
Reusability is a big part of both libraries. A large appeal of React is how simple it is to create reusable components and hooks that can be used all over a project, for example a custom hook can be made for handling form data or fetching from a REST API. This can be very powerful and the ease of creating custom functionality is simpler than in Angular, which leans towards more bespoke components. Although this does not mean that reusability is not possible in Angular – it is very possible to create reusable components and functionalities, and when possible this should be done. React’s focus on reusability allows for robust design patterns and abstraction of state functionality. Angular by design is more robust though and the enforced conventions cause a certain coding style to be followed, whereas in React, there is more room for creative problem solving.
Angular’s architecture facilitates testing, the standard testing tools bundled with Angular are Karma (test runner) and Jasmine (testing framework). An important reason for Angular’s architecture is testability, all applications parts can be tested easily in a similar way. Using dependency injection and faking, modules, components and services can be broken down into separated, easily testable chunks. React approaches testing in a different way; due to the lightweight nature of the library, components are tested using a third party test runner (usually Jest, a generic JavaScript test runner). When coupled with React Testing Library it is possible to mock components, however without a test runner like Jest to mock child components, React Testing Library will render child components in the tests, which is preferably avoided as to narrow the focus and scope of unit tests.
The differences in structure between the two libraries lead to larger components in Angular, with more specific code and larger scope. While in React, it can lead to smaller components with more reusability and smaller scope. Reusing components in Angular is more difficult, yet in React, this is more simple and lends itself toward reusability. React, in being the easier of the two to pick up it is also the easier one to mess up.
In these examples, we will be using both frameworks to create a simple counter component. For both frameworks, node.js and npm need to be globally installed.
Steps to create an app:
Run: npx create-react-app react-example
(Replace “react-example” with your project name)
This will generate a React application in the directory “react-example”
Navigate into the application with cd react-example
Start the application with npm run start
The application will be served on http://localhost:3000/ with the landing page (see below)
Create a new file within this folder called “Counter.jsx”
This is where we will create our component; start by exporting a function like so:
export default function Counter() {
return <div>Counter Component</div>
}
We want to see this component in our app to make sure it works, so add it to your App.js file, while removing the extra stuff from the landing page.
import Counter from './components/Counter/Counter';
function App() {
return (
<div>
<h1>React Example</h1>
{/* Our Counter component */}
<Counter />
</div>
);
}
Now some simple text should be visible on localhost: a header of “React Example” with some text underneath with “Counter Component”
We want this component to actually do something, so return to Counter.jsx
We need some state to hold the count, to show the state in the DOM and a button to increase the count.
import { useState } from "react"
export default function Counter() {
// The useState hook in React, used to store and update the value of state within a component
const [count, setCount] = useState(0);
// Our function to be called when the count button is clicked
function handleCountClick() {
setCount((previousValue) => previousValue + 1);
}
return (
<div>
{/* Using curly brackets, we can use JavaScript in the JSX template */}
<p>Current Count: {count}</p>
{/* Here using the onClick event from the button, we can call our handler function */}
<button>Count</button>
</div>
)
}
You should now have a simple React application that looks like below. Congratulations!
Steps to create an app:
Install the Angular-cli with: npm install -g angular-cli
cd to the folder you want the root to be in.
Run: ng new angular-example
(Replace “angular-example” with your project name)
This command will generate an Angular application in the directory “angular-example”.
It will ask if you would like to include angular-routing and what stylesheets you want to use for the project. For this project we will not need routing and this project is using CSS.
Navigate into the application with cd angular-example
Start the application with ng serve
The application will be served on http://localhost:4200/ with the landing page (see below), including some useful links and resources to get started.
Create your first component with ng generate component counter
to create our counter component.
Go to src/app/app.component.html in your IDE and delete everything.
Replace it with:
<div class="app">
<h1>Angular Counter</h1>
<!-- The selector for our counter component -->
<app-counter></app-counter>
</div>
The served app should now just have a header of “Angular Counter” and some text with: “counter works!”
Navigate to src/app/counter/counter.component.ts
Here we can see the TypeScript file for the component, this is where all the functionality and logic is housed.
In the @Component decorator, we can see: the selector (we used this in the app component), the templateUrl (this is the html template which will be rendered in the DOM), and the styleUrls (the stylesheets for making our app pretty).
Since we are making a simple counter, we need a count variable and a method to call when we click our count button.
import { Component } from '@angular/core';
@Component({
selector: 'app-counter',
templateUrl: './counter.component.html',
styleUrls: ['./counter.component.css']
})
export class CounterComponent {
// Our count variable, as this is TypeScript we should declare its type.
// This variable needs to be public to be accessed from the template.
public count: number;
constructor() {
// In the constructor, we initialise count's value.
this.count = 0;
}
// Our method to be called when our count button is clicked
public handleCountClick(): void {
this.count++;
}
}
Now we need something to render in the DOM, open the counter component’s html template in your IDE.
<div class="counter">
<!-- Using the double curly brackets, variables within the ts file can be easily rendered in the DOM -->
<p>Current Count: {{count}}</p>
<!-- We can access an event emitted from a child component with parenthesese, then use that to call our own method -->
<button>Count</button>
</div>
You should now have a simple Angular application that looks like below. Congratulations!
React feels more lightweight and focused than Angular as there is much less to learn, which is a significant contributor to its greater flexibility. For large scale applications, dealing with large amounts of data, Angular is probably the better choice. For a smaller application that requires speed and flexibility of development, React is likely the appropriate option. Of course both can be used for all kinds of projects, and both have their pros and cons. Angular provides security and structure, while React provides agility and speed. Both are excellent choices, and in being so different, provide different value to developers, businesses and projects.
Share this: