Unlock the power of PWA into your React Apps

Strengthen Your React Apps with PWA Features: Explore the Advantages

Unlock the power of PWA into your React Apps

Introduction

Progressive Web Apps can unlock numerous powerful features for your React apps, which is what we'll explore in this article. PWAs address many modern-day challenges without requiring heavyweight libraries or additional effort in your apps. This lightweight approach allows you to focus on your app's core logic and prioritize what matters most.

Many modern front-end frameworks support PWAs. You can implement them using their libraries or add them manually. Let's dive into the world of PWAs and explore how we can use and implement them in our apps.

Prerequisite

Before we begin, let me clarify who will benefit most from this article. If you are familiar with React, this article will be quite helpful for you. If you don't know React (You can go through this article to get started with React )or you are currently learning it, consider saving this article for future reference.

You can also use this article to implement PWA in different frameworks. You'll need to add the required libraries for your specific front-end framework, or you can add them manually. The steps for implementing manually, which I mention in this article, will remain the same for other frameworks as well. However, there will be some steps with minimal changes that need to be made for specific frameworks.

What is PWA ?

PWA stands for Progressive Web Application, which allows you to provide native app-like features in any web application using web technologies such as HTML, CSS, and JavaScript. These additional capabilities can make your web application function similarly to native mobile apps.

PWAs can add extra capabilities to your web app, providing features similar to those offered by native apps. You can incorporate native features such as Push Notifications, Offline Support, Quick Installation, Native-like Interface, Automatic Updates, Cross-Platform compatibility, and much more. This can give your app an edge over other apps available in the market.

Implementing PWA in your apps can make them more easily accessible and put you one step ahead of other typical apps available in the market.

Benefits after implementing PWA

After implementing PWA, numerous companies have experienced significant improvements in user sessions, engagement, and conversion rates. That's why companies like Flipkart, Uber, Forbes, and The Washington Post have decided to implement PWA in their web apps.

Here are the benefits that large companies have experienced after implementing PWA:

  • Flipkart :- Users spend 3.5 minutes on-site, compared to 70 seconds with the previous mobile experience. Users spend 3x more time on site. Users have a 40% higher re-engagement rate. Users have a 70% greater conversion rate among those arriving via Add to homescreen. Data usage is 3x lower

  • The Washington Post :- After launching their PWA, they saw a 23% increase in mobile search users who returned within seven days.

  • Uber:- Their PWA is fast and reliable, even on 2G networks, leading to increased bookings and user satisfaction.

  • Forbes:- Forbes' PWA saw a 43% increase in sessions per user and a 100% increase in engagement.

  • Pinterest :- After launching their PWA, they saw a 60% increase in core engagement and a 40% increase in user-generated ad revenue.

  • Trivago:- Trivago's PWA saw a 150% increase in user engagement and a 97% increase in clickouts to hotel offers.

These examples highlight how PWAs can significantly improve user experience and drive business growth.

So before we implement PWA, we need to understand some of topics that required for PWA.

Primary Components of PWA

To comprehend how PWAs function behind the scenes and what is required for their implementation, let's explore some of the key terms associated with them.

Manifest.Json File

The manifest.json file describes our app, including its name, icon, and other properties. This file informs the browser how to display the app to the user and is used for installing the app on the home screen.

A manifest.json file typically looks like this. You can learn more about the properties listed below here.

{
  "name": "HackerWeb",
  "short_name": "HackerWeb",
  "start_url": ".",
  "display": "standalone",
  "background_color": "#fff",
  "description": "A readable Hacker News app.",
  "icons": [
    {
      "src": "images/touch/homescreen48.png",
      "sizes": "48x48",
      "type": "image/png"
    },
    {
      "src": "images/touch/homescreen72.png",
      "sizes": "72x72",
      "type": "image/png"
    },
    {
      "src": "images/touch/homescreen96.png",
      "sizes": "96x96",
      "type": "image/png"
    },
    {
      "src": "images/touch/homescreen144.png",
      "sizes": "144x144",
      "type": "image/png"
    },
    {
      "src": "images/touch/homescreen168.png",
      "sizes": "168x168",
      "type": "image/png"
    },
    {
      "src": "images/touch/homescreen192.png",
      "sizes": "192x192",
      "type": "image/png"
    }
  ],
  "related_applications": [
    {
      "platform": "play",
      "url": "https://play.google.com/store/apps/details?id=cheeaun.hackerweb"
    }
  ]
}

Service Worker

This is the script that runs in the background, independent of the web page, and enables features such as offline support, push notifications, and caching. It intercepts network requests and can cache resources to enhance the offline experience.

A service worker is a type of web worker—a JavaScript file that runs independently from the main browser thread—in the background of your web application. Its purpose is to act as an intermediary between your web app, the browser, and the network.

Creating a PWA using React

We've covered the benefits of PWAs and some of their theoretical concepts; now, let's write some code and create a PWA project using React.

Step - 1 :- Creating a new React APP with a PWA Template

To get started, create a new React project using the cra-template-pwa template, which provides the necessary configurations and files for building a progressive web app. Enter the following command into your terminal:

npx create-react-app my-app --template cra-template-pwa

Replace my-app with the name you want to give your new React PWA project. This command will create a new directory with the specified name (my-app in this example) and set up a new React project using the cra-template-pwa template, which includes the necessary configurations and files for building a progressive web app.

Step - 2 :- Enabling Service Worker

Once your app is installed, open up your project in Visual Studio Code then open src/index.js file and change serviceWorkerRegistration.unregister() to serviceWorkerRegistration.register()

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import * as serviceWorkerRegistration from './serviceWorkerRegistration';
import reportWebVitals from './reportWebVitals';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://cra.link/PWA
serviceWorkerRegistration.register();

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

This will enable service worker capabilities in your app, meaning the service worker will be executed and installed in the background. Service workers can also enable background sync, allowing your app to synchronize data in the background, even when the user is not actively using the app.

Step -3 :- Customizing Manifest.json

This will serve as the configuration file for your PWA app. You can locate the manifest.json file under public/manifest.json

{
  "short_name": "First PWA React APP",
  "name": "First PWA React APP",
  "icons": [
    {
      "src": "favicon.ico",
      "sizes": "64x64 32x32 24x24 16x16",
      "type": "image/x-icon"
    },
    {
      "src": "logo192.png",
      "type": "image/png",
      "sizes": "192x192"
    },
    {
      "src": "logo512.png",
      "type": "image/png",
      "sizes": "512x512"
    }
  ],
  "start_url": ".",
  "display": "standalone",
  "theme_color": "#000000",
  "background_color": "#ffffff"
}

You can modify the name, short_name, and icons, which will function as the app icon and name once added to your home screen.

Here, we change the name to "First PWA React App". Feel free to modify it as you wish.

Step - 4:- Building the App

The next step is to build the app, which will create a production-ready version of your app in the build directory. To build the app, run the following command in the terminal

npm run build

Step - 5:- Running the app locally

The last step is to serve the production-ready version of your app located in the build directory. First, run the following command to install the 'serve' package globally:

npm install -g serve

The serve package offers a straightforward development server that hosts your PWA files locally. This is beneficial because PWAs frequently utilize service workers and other features that need a server environment to operate properly.

PWAs frequently utilize service workers to enable features such as offline caching and background sync. The serve package can host your PWA using HTTPS, which is necessary for service workers to function in many browsers (including Chrome).

Using serve enables you to mimic the production environment for your PWA locally. This can assist you in identifying issues early on and ensuring that your PWA functions properly when deployed to a production server.

Then run this command to start a server at http://localhost:5000 (or another available port) and serve your PWA from the build directory.

npx serve -s build

Add PWA to existing React Project App

If your existing app was created using create-react-app, you can easily add a service-worker.js file alongside index.js. This is because create-react-app (CRA) automatically searches for service-worker.js to include it in the build directory. In index.js, you can register your service worker like this:

if ('serviceWorker' in navigator) {
  // Register a service worker hosted at the root of the
  // site using the default scope.
  navigator.serviceWorker.register(`${process.env.PUBLIC_URL}/service-worker.js`).then(
    registration => {
      console.log('Service worker registration succeeded:', registration);
    },
    /*catch*/ error => {
      console.error(`Service worker registration failed: ${error}`);
    }
  );
} else {
  console.error('Service workers are not supported.');
}

Don't forget to create a manifest.json file in the same folder where your index.html resides.

The steps may vary for different frameworks, and you can add features and code according to your needs.

Bonus

So that's it; this is how you can implement PWA in React apps, adding features and taking it to the next level with more options for your apps and users to generate more business.

As we know, PWAs can incorporate some native app-like features and provide a native-like user experience. What if I told you that you could publish the same PWA app to the App Store or Play Store? Yes, you can do that. PWABuilder helps developers build and publish PWAs with ease.

They offer easy-to-follow tutorials and steps that help you understand and publish your apps more quickly. This can be advantageous if you plan to create a native app for your web app, potentially saving time and costs for your business.

Conclusion

In conclusion, Progressive Web Applications (PWA) provide an excellent way to enhance user experience and engagement in your web applications. By extending the capabilities of traditional web apps, PWAs offer a native app-like experience, including features such as push notifications, offline support, and automatic updates.

Implementing PWA in your React applications is relatively straightforward, thanks to the availability of libraries and detailed documentation.

With their proven ability to drive business growth and user engagement, as evident from the success stories of companies like Flipkart, Uber, and Forbes, PWAs are certainly a worthy addition to your web development toolkit.

Thank you for reading my article. Please Follow Me, Feel free to comment and share your suggestions/thoughts 😊

Resources

Did you find this article valuable?

Support Pradhumansinh Padhiyar by becoming a sponsor. Any amount is appreciated!