12 May, 2021

10 min.

Strategy and Tips for Migrating to React

Migrating to React allows developers to ship features faster and makes an app easier to maintain. Plus, it can be done painlessly, as an easy, incremental process. However, before you jump into it, learn more about best practices and possible problems ( + how to overcome them). Just to do it right.

Piotr
Github LinkLinkedin Link
Full Stack Developer
Marek
Github LinkLinkedin Link
Full Stack Developer
Olga
Linkedin Link
Editor
Chapters in handbook:

More chapters are coming!

Notify me

Introduction

Decision about migrating your app or website to another technology sounds like a tough one to make. Doubts are understandable: you can’t afford to shut it down for a while or risk making a mess. But if your chosen technology is React, the migration becomes a lot easier.

React can be migrated to incrementally. New features can be shipped with React, so that developers are able to fully focus on the JavaScript part without thinking too much about the server templating system.

But of course, migrating introduces both opportunities and risks, and it’s good to learn a few best practices before beginning.

In this article, we’ll be investigating:

  • the opportunities and risks of migration to React,
  • the best practices for painless migration,
  • how to migrate large scale apps,
  • how to migrate from Python, PHP and AngularJS (with many practical examples).

If you are looking for answers, or maybe even find yourself desperate for some tips, follow along.

Why migration from old web technologies is important

Digital products continuously evolve. What was once impossible or too costly to build and maintain is now a typical feature

Websites where every little change of the state of the application caused a full reload (such as switching tabs in a menu) used to be very common. Nowadays such state changes can be applied immediately, without reloads, since they can be made to rely on JavaScript.

Opportunities of migration

By migrating to a new front-end technology you may:

  1. Improve the speed of your app.
  2. Improve your conversion rate.
  3. Separate the frontend and backend completely so that they do only their respective work without intermingling.
  4. Ship new frontend features faster.
  5. Reduce the risk of creating spaghetti code.

Migration from old approaches opens new possibilities. It’s easier to scale and maintain the app, and more convenient to make changes.

Migrating to React

React can be introduced gradually. Initially, developers can create reusable components that receive data from PHP templates. Then, those components can be modified to receive data from a separate server call as it is usually done in modern frontend applications.

You don’t need to migrate the whole app

That’s one of the greatest benefits of migration to React. There is nothing wrong in having only a part of your app written in React as it can freely work alongside an existing solution. However, you need to make sure that their local states don’t communicate directly. 

Risks of migration to React

Migration to React brings many opportunities, but you also need to be aware of a few risks (and ways of coping with potential problems).

SEO indexing issues

People are often concerned about the SEO score of apps which rely heavily on frontend code. 

In such situations SSR comes into play. It first renders React code on the server, returns it to the user and reuses it later when JavaScript finishes parsing. 

However, you need to be aware that some of your APIs will have to be mocked on the server. For example, if you use virtualized lists which are used to render only elements visible on the screen (so that the user’s device doesn’t use too many resources without a reason), you will have to mock the height of the area visible for the user because the server has no knowledge of the end user’s screen height.  The height needs to be artificially set on the server so that the first paint contains data which can be then parsed by search engines.

Fortunately, once React finishes loading and reuses the pre-rendered template, it is back to normal.

Risks of migrating from a template-based solution

You need to be aware that, although React is fast, it won’t make your app faster just on its own. If tacked onto an existing stack of frameworks and libraries that are slow, React is likely to just make things even more sluggish.

However, if you start replacing existing components with React and phasing out old libraries, you will most likely see a substantial increase in performance.

Before you start: migration best practices

You need to prepare for the migration process carefully. 

Measure first

First of all, measure all the impactful metrics.

Among the metrics you should measure are:

  • size of the app,
  • load time,
  • time to interactive,
  • conversion rate of particular features. 

It will be useful for later comparison after you introduce React.

Do it step by step

In order to start the migration step by step, first:

  • Identify a small component that you would like to try in React – it may be an existing component of your app or a new feature.
  • Pass some data directly to it and test how it behaves together with your templating engine.
  • (optionally) Set up a state management tool such as Redux and test the integration, but you can do it later as well when you find it necessary.
  • Once it’s set up you may find parts of your web app such as modals, filters, videos or lists that do not work with the new solution.
  • Rewrite them to React and measure the outcome based on the metrics from before the migration.

Tip: As mentioned earlier you may also just add React without rewriting the existing codebase if you see it fit. 

Maybe only a part of your application relies heavily on the frontend and the rest should remain as is.

Additional tips

1#

Many web apps are still built on dynamic PHP templates which often utilize third-party, deprecated frameworks such as Kohana. 

In such cases, when implementing new features that heavily rely on frontend technologies (such as geolocation, live messaging, streaming or drawing) developers need to make sure that the client’s state, stored in structures utilizing the old approach, is synchronized with the one used for React so that a user doesn’t experience UI glitches. 

2#

React is built using virtual DOM so if you need React to know about a certain value stored somewhere in an HTML tag (thus directly using the browser API such as “document.getElementById”) make sure that you pass it using a layer of abstraction. If you do it differently, React will not react to changes that happen in the DOM. 

By “layer of abstraction” we understand (for example) a React method exposed to the outside (non-React) app which may then be called together with any old code whenever you need an update in React.

It will also allow you for easier move to React during later development.

Let’s get to practice! We’ll investigate:

  • how to migrate large-scale apps to React, 
  • how to migrate from Python to React,
  • how to migrate from PHP to React,
  • how to migrate from AngularJS to React.

Migrating large-scale apps to React

Large-scale apps’ migration often raises many concerns. If that’s your case, you need to remember that with React you don’t have to migrate the whole app at once.

You should avoid trying to achieve too much in a short time. The process of migrating from an old technological stack to a new one should occur incrementally and painlessly.

Start with changing one part of your application.

Example

Let’s say you run a travel agency company. A user may find a list of potential trips on your website. 

The list may look like this:

Migrating to React - large-scale app example.
Source

Let’s rewrite this component to React:

Learn how easy migrating to React is by seeing how to rewrite a simple component.

Then let’s insert it into the DOM:

import React from 'react';
import ReactDOM from 'react-dom';
import ListItem from './components/ListItem;


const listItemsElement = document.getElementById('react-list-root');


if (listItemsElement) {
  try {
    ReactDOM.render(
<>
  {listItems.map((listItem, index) => <ListItem key={index} {...list} />)}
</>, listItemsElement);
  } catch (error) {
    console.error(error);
  }
}

And voilà: our list of trips is now displayed as a React component.

Tip: It is a good practice to be able to switch between a legacy solution and a new one written in React on demand so that you are capable of running A/B tests. This way, you can monitor the conversion rate or receive feedback from your testers about the transition.

Migrating from server-side templates to React SPA

Small components make it easier

React was first designed with the purpose of creating small JavaScript components and inserting them into a page generated by the templating system on the backend. Thanks to that migrating from this approach is easier than migrating from another JavaScript framework.

You may want to start very slowly with just one React component on one page and then add subsequent ones. 

When most of your pages consist of primarily React components, you may consider rewriting them in the form of a single page application.

React SPA

A single-page application (SPA) is a web application or website that interacts with the user by dynamically rewriting the current web page with new data from the web server. On the other hand, the traditional method where a browser is loading entire new pages. 

SPAs ensure faster transitions, because only data has to be fetched from the server with none of the markup. 

The most popular solution for building an SPA in React is React Router.

Changing a template-based component to a React component

You will probably notice that once you change a template-based component to a React component, the way the element appears visually changes. 

React is a frontend library which means that the JavaScript code needs to be downloaded, parsed and only then it can be applied to the DOM, while the solution based on templates is already generated and attached to the DOM. 

It simply means that you will most likely see a moment of no content in that place and then it will appear. 

If this is not something that you expect or want then consider SSR.

SSR is a process that generates markup of your components on your server and attaches it directly to the DOM so that your users visually don’t see any difference.

Now, let’s dive into details and investigate how the migration from Python and PHP to React may look like, and what to look for.

Migrating from Python to React

Migrating to React from Python.

When your backend is written in Python using a template engine such as Cheetah, you may slowly migrate to React by encapsulating small components and calling them with React.

Examples

1. The component may look like this in the beginning:

Migrating from React to Python code example.
Source

2. You may want to create a Python method which loads a React component with certain properties:

Migrating from React to Python code example.
Source

And you can do so with subsequent parts of your application that you consider “components”.

3. Once your page is mostly comprised of React components, you should replace everything with just one call to render the page with React in a way similar to:

Migrating from React to Python code example.
Source

Migrating from PHP to React

Migrating to React from PHP is easier with a template engine like Twig.

When your backend is written in PHP using a template engine such as Twig, you may similarly to the case described in Python, slowly migrate to React by encapsulating small components and calling them with React.

Examples

1. At first, your call to a component might be similar to this:

echo $template->renderBlock('shopping_cart', ['prop1' => 'value1', 'prop2' => 'value2']);

Create this component in React and call it using your PHP method for calling React components. 

2. The call of this method may look like this:

<div id="shopping-cart"> <?= render_component("ShoppingCart", array("items" => items, "title" => "My List")) ?> </div>

3. Or you may attach the React component using JavaScript:

const shoppingCart = document.getElementById('shopping-cart');

if (shoppingCart) {
  try {
    ReactDOM.render(<ShoppingCart {...(shoppingCart.dataset)} />, shoppingCart);
  } catch (error) {
    console.error(error);
  }
}

4. And call it with data from PHP:

{% block body %}

<div
  id="shopping-cart"
  data-item-id="{{ item.id }}"
  data-item-title="{{ item.title }}"
  data-item-price="{{ item.price }}"
></div>
{% endblock %}

And now we can use data passed from PHP in React!

Migrating from AngularJS to React

Migrating to React from Angularjs.

AngularJS used to be a revolutionary freshness in the frontend world back in 2012. 

We owe a lot to its approach but by today’s standards it is obsolete so if there’s an active app written in AngularJS, it should be migrated to a new technology – sooner rather than later.

The migration process from a JavaScript framework to React is more difficult than migration from a server template language. It is still possible with a little bit more care and patience.

As always the migration should happen gradually, one component at a time. 

It is a tedious task as both solutions (AngularJS and React) use different approaches for rendering the UI underneath.

Replacement of the way the UI is rendered

Fortunately, this problem is so common that good people have created generic ways to bridge the two frameworks so that a gradual recomposition is simpler – it’s called “Angular2React”. 

Examples

How to use it?

Let’s have a look.

Migrating to React from Angularjs steps.
Migrating to React from Angularjs steps.
Migrating to React from Angularjs steps.
Migrating to React from Angularjs steps.
Migrating to React from Angularjs steps.

Bridging business logic between AngularJS and React

Eventually you will need to port business logic from AngularJS to React. 

In order to do so it is a good idea to dispatch actions (Redux approach) inside AngularJS services this way:

Example

const sessionActionCreators = {
  logout: () => ({type: LOGOUT})
  ...
};
// Create factory for actions
app.factory('SessionActions', () => {
  return mapValues(sessionActionCreators, (actionCreator) => (...args) => {
    store.dispatch(actionCreator(...args));
  })  
});
// Usage:
angular.module('Some module', []).factory("SomeService", (SessionActions) => {
  SessionActions.logout();

Replacing the router

Finally you will have to replace your router. This is going to be time-consuming as the whole application depends on it. 

Make sure your application is thoroughly tested once you finish the transition.

Migrating to React – everything you need to remember

Migrating large-scale apps, or apps built with Python, PHP or AngularJS, to React can be simple if it is approached correctly.

How can you ensure that?

We’ve created a handy checklist for you, to help you take care of all the important details. You can find it below.

How to migrate to React painlessly:

  1. Have a clear goal in mind of why you want to migrate your application.
  2. Draw your plan of migration reasonably so that you don’t plan for too much in too little time.
  3. Migrate one small chunk of the frontend codebase at a time.
  4. Create a bridge between your existing UI solution and React so that they can work together.
  5. Start from the parts that seem easiest to port.
  6. Measure important metrics of your app before you start any migration and measure them afterwards.
  7. Set up proper A/B tests.
  8. Consider SSR (server side rendering) if you find the way React components coexist as not user-friendly.
  9. Once a whole page is built with React components it’s a good time to render it all with React using one call instead of multiple.
  10. When all of your pages are written in React, use React Router to create a SPA.
  11. Consider SSR if you are concerned about SEO.

Liked this chapter?

Awesome! We’ll be adding new content on this topic soon. Want to be notified?