Migrating from Angular to React – CTO Playbook

Type
outsorce
Time to read
20 min
Data
February 4, 2024
Share
Migrating from Angular to React – CTO Playbook

The constant changes in JavaScript and other frameworks such as React have brought massive improvements to writing code. However, it has also been a thorn in the flesh for software developers trying to match up with the rapid advancements in the field while maintaining older, legacy programs such as Angular 1.

Considering Angular 1 web applications are piling by the day, it’s increasingly becoming more difficult to scale the UI and add progressively more complex features. While this differs with each use case, and the amount of information that needs to be processed, the most common result is performance degradation, rendering slowdowns, troubles with interactivity, and sometimes race conditions.

To keep up, most companies are moving to React. However, migrating from Angular to React is no walk in the park, thus it needs to be done right and by expert professionals.  This is essential to avoid unprecedented problems and costs in the future. Fortunately, for you, our developers at Appvales have successfully worked on countless projects that required migrating from Angular to React. You can rest assured that we will handle your end-to-end product development flawlessly.  

Appvales can also collaborate with your product team through our dedicated mobile development model. We are a software development company with more than a decade of experience in software development.

When you think of migrating, deep knowledge for both frameworks is a must. In this article, we’ll explore:

• the opportunities and risks of migrating from Angular to React

• the best practices for easy migration

• how to migrate large scale apps

We’ll describe these techniques in great depth to help you be successful with code migration. Let’s get started!

Why migrating to React is a Good Choice?

Do you probably ask why migrate to React? Is the process worth it? Is it because it’s the developers’ most loved framework?

Well, there are so many reasons why you should choose to migrate from Angular to React. Here are some of the best ones:

React’s API is simple

React has nine lifecycle methods that you can use to control your components. However, you might only need to use a few, even in the case of a mature React application.

In addition to that, you need to know a React ES6 class component method setState(). This is used to update the internal components state. With React, you do not experience a steep learning curve like you would in other frameworks. Essentially, it’s a view library that was designed to solve one problem. And it does that well!

React is an innovative place

The building blocks in React offer you the flexibility you need to solve specific challenges. They are easy to exchange if the need arises. The ability to swap in React permits a software developer to experiment with new and acceptable approaches. This makes React a better innovative space.

While Angular provides its own solutions, the React core can be exchanged for other building blocks such as Preact – something which is not possible with Angular.

Unidirectional Data Flow

Unlike Angular, React does not have a two-way data binding. Instead, React works upon the rule of unidirectional data flow, meaning that the process of debugging is less complicated. With React, the child components are inserted within higher-order parent components. Additionally, React offers its users total control over the native HTML elements. This means the React state management can be predicted and easily maintained.

JSX syntax blends well together with javascript

JSX is a React syntax used for component building. It also works well with JavaScript and HTML. React code bears a resemblance to true JavaScript, and it strongly relies on more functional programming principles. JavaScript can compose and manipulate DOMs, and developers can use built-in functionalities such as filters and maps. In this manner, the total potential of JavaScript is used within an HTML code, and this process will result in a rapid development pace.

Angular, on the other hand, does not mix view and logic.

React is powered by a faster engine

When it comes to framework engine comparisons, the engine that powers React is much faster than that powering Angular applications. For instance, to execute JavaScript code in the browser, Angular might need around 5000ms, as compared to React, which requires slightly less than 1000ms. A quicker framework offers a better user experience, lesser time waiting to render elements in the DOM, and a website that responds quickly.

Lightweight Components

React defines its components in two different ways: ES6 class components and functional stateless components. Although stateless components are functional, they don’t have any boilerplate. This means, developers should use them when they need to get access to the lifecycle methods or component state. By doing so, it guarantees developers that the components are lightweight, small, and reusable.

Functional Programming

Functional programming is a declarative programming paradigm where software is developed by applying and composing functions. It feels more natural working in React and its ecosystem, mainly because of its close resemblance to JavaScript. In React, functions should be defined with no side-effects to make them predictable as they return the same output all the time and are composable – as functions of a higher order can be used to compose them into each other. Software programmers think of React as the leader of functional programming when compared to other JavaScript libraries.

Community

Every developer fancies a good community, and it’s an essential factor to consider when choosing a framework. The React community is highly supportive, and you’ll often get the answers you are looking for. And to top that, React developers have a deep desire for innovation and are constantly experimenting every day, coming up with better solutions. For sure, the larger the community, the better the framework!

Challenges and Risks of Migrating from Angular to React

An Angular to React migration comes with many benefits, but you also need to know that there are a few challenges and risks associated with it. As such, the importance of understanding how you can deal with it cannot be overemphasized.

Without further ado, let’s look at some of the risks and challenges of migrating from Angular to React.

Risks of migrating from a template-based solution

Please note that even though React is quite fast, it will not make your application perform faster all on its own. And what’s worse, if a developer adds it to an existing stack of frameworks and libraries that are not quick, React will most likely make things slack even more.

However, if you replace the older components with React and take out old libraries, you will probably see a substantial increase in performance.

SEO indexing issues

With the increased need to improve a website’s online visibility, many people are concerned about the SEO score of applications that strongly rely on frontend code. In these scenarios, SSR is adopted. Initially, it renders React code on the server, then gives it back to the user, and reuses it later when JavaScript is done parsing.

However, you will need to mock some of your APIs on the server. For instance, if you use virtualized lists to render elements that are only visible on the screen, you will need to mock the height of the area visible for the user as the server does not know the end user’s screen height.  The height needs to be set artificially on the server to ensure that the first paint contains data parsed by search engines. But the good thing is that the moment React is done loading and reusing the pre-rendered template, it goes back to normal.

The Right Migration Strategy

Two popular refactoring approaches that can be adopted in general software systems refactoring are the Rewrite and Strangler patterns.

Rewrite vs. Strangler pattern

If you opt for Rewrite, you will start with a brand new application and then copy existing application features using a new framework. It will work incredibly well especially if you are yet to release the application. Without existing users, you will not be pressured to upgrade and maintain it.

Advantages of Rewrite

  • You have a clean architecture that fits the new framework
  • There is no need to build integration bridges between old and new code, so you enjoy high development speed with fewer hassles.

Disadvantages of Rewrite

When you want to offer your app users new features, you will have to write them in the old framework. This is difficult to do because you can’t bring in new app features until it fully copies the existing functionality. Generally, it is a challenging approach that is time-consuming, especially if you already have an app in development. Therefore, in working businesses, you will find that oftentimes, Strangler patterns are used for refactoring.

The Strangler pattern, on the other hand, tackles the refactoring problem differently. It assumes that you replace old components with new ones, taking care of stitches between frameworks. Thus, you gradually remove old code and deliver new features using a new framework.

Advantages of the Strangler Pattern

  • Developers can implement new features using a new framework

Disadvantages of Strangler Pattern

  • Developers are burdened with maintaining the interaction of new and old code
  • Developers have to align the new framework architecture with the old framework architecture, with the possibility to refactor the new framework code too.

Overall, these two approaches have many benefits. A noble option is to use the Strangler pattern, select more significant independent parts and rewrite each one independently before connecting all the parts. You need to figure out how to pick these parts to make the most effective refactoring.

Angular router as a splitting point for refactoring

When you look at the top-level architecture of the Angular application, you will notice that it’s generally an Angular router that assigns all routing events tasks to Angular components. If it is a medium-sized application, you will probably have a large number of routes that use Angular features as handlers. Every page handled by the router is independent (to a certain level) from other pages. So, in this case, the technique of rewriting every page that corresponds to the Angular route independently will be a noble one.

This is the general idea behind it:

  • Make sure that you clearly understand your company’s plan for delivering new features
  • Select the routes that are used for these particular features
  • Set up new react components for every route you would have selected. This will simultaneously refactor Angular into React, and will deliver new features.

Here’s one line of code to turn any Angular component into a React component:

1. Installation

# Using Yarn:
yarn add angular2react angular angular-resource react react-dom @types/angular @types/react @types/react-dom

# Or, using NPM:
npm install angular2react angular angular-resource react react-dom @types/angular @types/react @types/react-dom --save

Usage

1. Save a reference to the $injector

let $injector
angular
.module('myModule')
.run(['$injector', function(_$injector) { $injector = _$injector }])

2. Create an Angular component

const MyComponent = {
bindings: {
fooBar: '<',
baz: '<'
},
template: `
<p>FooBar: {this.$ctrl.fooBar}</p>
<p>Baz: {this.$ctrl.baz}</p>
`
}

3. Expose it to Angular

angular
.module('myModule', [])
.component('myComponent', MyComponent)

4. Convert it to a React Component

import { angular2react } from 'angular2react'

const MyComponent = angular2react('myComponent', MyComponent, $injector)

5. Use it in your React code

<MyComponent fooBar={3} baz='baz' />

You need to know that there is no single way to do the migration from any framework to another framework. Migration is always different depending on a case’ requirements.

Execution Plan

You can use the divide-and-conquer plan to migrate the forms. Here’s how this can be achieved:

  • Bigger chunks of challenges are divided into smaller ones.
  • If your program has more than100 forms, group and address the common elements at the same time.
  • Create a Component template that groups all similarities that the forms have, then proceed to move them all in one large file. That allows me to test them from a single file, and search and replace becomes easier.
  • Ensure that all form elements are JSX compatible.

Angular to React Migration Best Practices

  1. Migrate one component at a time– Rewriting the whole front-end can be very risky, as it can prevent you from developing new features for quite some time. It’s always a better option to do it step by step, one component at a time.

Here’s a good example:

2. Generalized bridge binds ngRedux’s state to React– A generalized bridge component, can allow developers to wrap React components to be used also in the Angular application. Its basis is on the reactDirective from ngReact that executes the basic interactions with Angular.

Here’s a bridge code that adds the state from ngRedux to the React component by default:

smartlyReactBridge.js:

import React from 'react';
import {Provider} from 'react-redux';

const wrapProvider = WrappedComponent => ({store, ...props}) => (
<Provider store={store}><WrappedComponent {...props} /></Provider>
);

angular
.module('SmartlyApp.services')
.factory('smartlyReactBridge', function(reactDirective, $ngRedux) {
return function(Component, propNames, directiveOptions = {}, otherProps = {}) {
return reactDirective(
wrapProvider(Component),
propNames,
directiveOptions,
{ store: $ngRedux, ...otherProps }
);
};
});

3. Binding a React component to an Angular component– After porting it to React, render it in the campaign management view. Here’s an example of how it was done:

CampaignLabels.js:

// @flow
import CampaignLabels from './CampaignLabels.js';

4. Next step is to save the matrices of the Angular app in order to compare with the React version. This includes load time, size of the app, and interactive time.

5. If you are implementing new features that strongly rely on front-end technologies (for example streaming, geolocation or live messaging) you should make it a point to synchronize your client’s state, and it’s stored in structures utilizing the old approach, with the one used in React. This will ensure that a user will get a good experience and not face any UI glitches.

6. Work first on the parts that appear easy to port, once done with these you can then proceed on the more challenging ones.

Angular to React Migration Tools

You can make use of the following Angular to React migration tools in your project:

.gitignoremake react and angular peer dependencies.npmignoreadd tests, update docskarma.conf.js🌅package.jsonv3.0.2package-lock.jsonupdate npm lockfile, againREADME.mdupgrade deps, move @types/abc to peerDependenciesindex.tsxupgrade deps, move @types/abc to peerDependenciescircle.ymlupgrade node version in circlelogo.png🌅test.tsxupgrade deps, move @types/abc to peerDependenciestsconfig.jsonupgrade deps, move @types/abc to peerDependenciesyarn.lockupgrade deps, move @types/abc to peerDependenciesLICENSE.md🌅logo.psd🌅

We Can Migrate Your App from Angular to React

The purpose of every library or framework is to provide developers with solutions that enhance productivity and can adapt to the ever-changing demands in the field. Migrating from Angular to React is a great choice because React has an incredible library that comes with a myriad of possibilities. If you want to migrate from Angular to React, get in touch with Appvales. We will handle the task with the best Angular to React migration tool to deliver the right solutions for you.

FAQ

Should I move from Angular to React?

Making a decision about migrating your website or app to a different technology seems like a tough one to make. It is very crucial to remember that Angular is a framework and React is a library, and this influences the way we compare the two. A library is just one part of your application and this makes the learning curve very small. On the other hand, a framework is quite big and you will need to stick to their standard way of doing things and you’re constrained to do everything, in this case, the Angular way. The building blocks in React give developers the flexibility to select the ones that best suit a particular project. These building blocks are quite easy to exchange if the need arises. This ability in React permits a software developer to experiment with new approaches that can be taken in by the community. This makes React a better innovative space.

Is it easy to shift from Angular to React?

Migrating from Angular to React can appear seemingly like a daunting task. If done correctly with the right expertise, the process becomes much easier. You need to migrate one component at a time and follow Angular to React migration best practices. Rewriting the whole front-end can be very risky because it can stop you from developing new features. In such a case, seeking expert help from Appvales will ensure the process is as seamless as possible.

Can you migrate an existing Angular codebase to React?

When using Rewrite, you will have to start with a brand new application which you then need to struggle to copy existing application features using a new framework. The Strangler pattern, on the other hand, tackles the refactoring problem in a different manner. It assumes that you replace old components with new ones, taking care of stitches between frameworks. Thus you gradually remove old code and deliver new features using a new framework.