Revolutionizing Web Experiences: A Beginner’s Guide to PWA with React

Embark on a journey to craft seamless, responsive, and offline-ready web applications.

Rutvi Patel
Simform Engineering
10 min readDec 4, 2023

--

A Beginner’s Guide to PWA with React

Have you ever noticed a small Install button or the Add to Home Screen option while enjoying melodious tunes on Spotify or scrolling through your favorite shopping or news site? Curious about the mechanics behind it?

Let’s dive into the exciting world of Progressive Web Apps, which allows you to supercharge your web applications by creating a seamless user experience that blends the best of both web and native applications.

What is PWA?

PWA stands for Progressive Web Apps, which leverages modern technologies to offer a responsive, reliable, and engaging experience to its users. In addition, it helps developers combine the best features of traditional web apps and platform-specific apps, be they Android or iOS, all with a single codebase.

PWA follows the “Progressive Enhancements” design philosophy that prioritizes accessibility and inclusivity. This is a layered approach to a design, which ensures the provision of basic content and functionality to all users regardless of browser or device capabilities and then progressively enriches the experience with advanced features for the users with the latest device and browser capabilities.

Key Benefits and Features of PWA

Cost-Effective Development & Maintenence:

  • With the adoption of PWA, we can develop a single codebase that functions across multiple platforms, including Web, Android, or iOS. This not only reduces time, effort, and resources for the initial development of an application but also eliminates the efforts to maintain a separate codebase for each platform.
  • Besides this, PWAs can be easily deployed and updated through the web. Hence, the time and costs of App registration, maintenance, and app review process can also be eliminated.

Better SEO results

  • PWA takes benefits of traditional web search engine optimization techniques, which makes them more discoverable and compatible with search engines. This compatibility ensures that search engines can effectively crawl, index, and rank PWAs higher in their overall search results.

Native App like User Experience

  • One of the core perspectives behind PWA is to provide a native app-like experience to users. PWAs can be installed directly from the web app using the Add to Home Screen button or Install icon, which can be found at the top right corner of the search bar.
  • Upon installation, users can get the app icon with other platform-specific applications. The installed PWA provides the exact same native app-like look and feel. It launches as a stand-alone application, delivers a fully responsive and seamless user experience, displays push notifications, uses device features, and many more…

Offline Accessibility

  • Instead of redirecting users to the default offline pages, PWAs keep operational despite poor or no network connectivity. With the help of service workers, PWAs effectively cache the response of network requests, data of visited pages, and global stylings and retrieve them when needed. This strategic caching mechanism ensures that, even without an internet connection, users can continue navigating through the app without disruptions.

Using the device features

  • PWAs enrich the user experience by accessing the device features according to device or browser capabilities. This inclusive approach encompasses a wide array of functionalities, ranging from camera and microphone access to geo-location services, contacts, payments, device orientation, motion, push notifications, seamless authentication through inbuilt fingerprint scanners, and much more…
Check out https://whatpwacando.today/ to know more about its features.

PWA Application Structure

Now, as we have explored the amazing benefits of PWA, let’s dive a bit deeper and explore behind the scenes of this technology — the code building blocks of its architecture, which makes the applications so dynamic and user-friendly.

  1. App Shell
    The fundamental structure of the application that loads foremost when the user opens the app. It provides the basic user interface and is often cached to reduce the initial load time, especially in the case of low or no internet connectivity. The app shell also plays a significant role in displaying the web push notifications.
  2. Web Application Manifest File
    This JSON file acts as a pivotal guide for browsers to transform web apps into app-like experiences. The web App manifest file contains the metadata information for the app, such as name, description, app icons, initial page, etc. As soon as the browser connects to the network, all the necessary resources get cached. It allows installing applications on the device’s home screen according to the OS.
  3. Service Worker
    A service worker is the backbone of PWA. It is a javascript file that runs in the background, even if the application is closed. Service Workers allows us to handle network requests, push notifications, synchronization, and other PWA features. Apart from this, it also helps to provide an uninterrupted experience to users with different caching strategies and asset management.
  4. HTTPS
    As PWAs strive to deliver a secure and responsive user experience, adopting HTTPS emerges not only as a best practice but as an essential element. HTTPS encrypts the communication between the user’s browsers and the server to safeguard it from potential threads, which is important for the functioning of service workers.
  5. Cache Storage & IndexedDB
    These are the two most important components for providing offline support to the user. Cache storage stores the data of frequently visited pages, such as scripts and images, statically (upon the first load) or dynamically (after visiting the route). IndexedDB is a transactional key-value database in the browser, which allows a large amount of structured data like files, blobs, objects, or arrays and also allows to access it asynchronously. IndexedDB can contain multiple databases with multiple data stores inside them, which can be efficiently used in storing the data of background & periodic synchronization.

Service Workers: Architectural Pillar of PWA

The service worker script acts as a bridge between web applications and the browser, which is essential to enabling powerful features, such as offline functionality, push notifications, efficient caching, background sync, and many more...

Let’s explore how service workers play a pivotal role in the ecosystem of PWA by understanding its lifecycle.

Service Worker Lifecycle

  • The lifecycle of a service worker is crucial for managing the behavior and performance of the service workers effectively.
Service Worker Lifecycle
  • The process begins with loading the root file. This step will register the service worker script with the browser using the navigator.serviceWorker.register().
  • During the registration process, the two phases are possible.
    1. Installation:
    After the registration, the browser will download and install the service-worker script. If the install event is being triggered for the first time; the essential resources will be cached.
    2. Activation:
    After the installation, the service worker enters the activation phase, which is considered the best time to clean up the old cache.
  • Once the service worker is activated, it can control all the pages within its scope. It can intercept network requests, manage caches, and handle various events. Moreover, the service worker will only get active if no old service worker instance is running. To install the new version of a service worker, we need to close the existing tab and re-open it, as it’ll be attached to the overall domain. Otherwise, one can use the skipWaiting option from the Application tab of developers tools.
  • The browser will consider installing the updated version of the service worker file only if the JS code is changed by one or more bytes. The registration step checks whether the service worker file has been changed. If it’s not changed, the install event won’t be triggered.
  • Once the service worker is activated, it enters idle mode, and after a specific time of inactivity, it’ll be terminated. (not unregistered; it’ll be in the sleep state and will wake up as soon as any will event happens, such as a Fetch request from any file)

Creating PWA with React

Now, it’s time to turn the theory into an action. In this blog, we’re going to cover the registration & installation part for service workers.

PWA with React (using CRA)

  • Create a React Application with npx create-react-app my-app or npx create-react-app my-app — template typescript
  • Now in /public directory, update the manifest.json file.
{
"name": "PWA-demo",
"short_name": "PWA-demo",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "/images/logo48.png",
"type": "image/png",
"sizes": "48x48"
},
{
"src": "/images/logo72.png",
"type": "image/png",
"sizes": "72x72"
},
{
"src": "/images/logo96.png",
"type": "image/png",
"sizes": "96x96"
},
{
"src": "/images/logo144.png",
"type": "image/png",
"sizes": "144x144"
},
{
"src": "/images/logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "/images/logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff",
"description": "PWA + React Demo Application with CRA",
"lang": "en-US"
}
  • Create a /images folder in the public directory and put all the necessary image files inside that. You can use https://www.pwabuilder.com/imageGenerator to generate the icons for Android and iOS. Along with this, create one offline.html file in the public directory to show when the user does not have an internet connection and requests content that has not yet been cached.
  • Now, create the service-worker.js file in the public directory to handle the install, update, and fetch events.
// Set a name for app's cache
const cacheName = 'my-app-cache-v1';

// Define the files to be cached for offline use
const filesToCache = [
'/',
'/images',
'/index.html',
'/manifest.json',
'/favicon.ico',
'/offline.html',
];

// Listens the service worker installation event
self.addEventListener('install', function (event) {
console.log('installing service worker...', event);
// Precache the app shell during installation
event.waitUntil(
caches.open(cacheName).then(function (cache) {
console.log('Precaching app shell...');
cache.addAll(filesToCache);
})
);
});

// Listens the service worker activation event
self.addEventListener('activate', function (event) {
console.log('activating service worker...', event);
// It'll wait until the clean up will be done, so that the fetch won't serve results from old cache
event.waitUntil(
caches.keys().then(function (keyList) {
return Promise.all(
keyList.map(function (key) {
if (key !== cacheName) {
console.log('removing old cache...', key);
return caches.delete(key);
}
})
);
})
);
// It ensures that whether service workers are installed or activated correctly or not.
return self.clients.claim();
});

// Listens fetch events
// It requests for data from the Internet, and if the internet connection is not available, it returns the offline page.
self.addEventListener('fetch', (event) => {
event.respondWith(
caches.match(event.request).then((res) => {
return fetch(event.request).catch(() => caches.match('offline.html'));
})
);
});
  • Now, it’s time to register the service worker. Go to the index.html file, and add the script inside the body of the HTML file.
<script>
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker
.register('./service-worker.js')
.then((reg) => console.log('Registered service worker!'))
.catch((err) => console.log('Failed to register service worker: ', err));
});
}
</script>
  • Run the application and test it! You will find a small install icon on the top right corner of the browser. Check the PWA compatibility with the lighthouse report from the developer's tool.
Lighthouse report for web app
If the content of the service worker file is changed to more than one byte, then the browser will consider installing the new version of the service worker. The new version will only be installed if an older version is not running
Installing PWA on the device

Checkout the source code: https://github.com/Rutvi25/PWA-Demo/tree/pwa-cra-demo

PWA with React (Using Vite + React)

  • Create a React Application with npm create vite
  • Install the Vite-PWA plugin using npm install vite-plugin-pwa — save-dev
  • Create a /icons folder in the /public directory and put all the necessary image files inside that.
  • Update the vite.config.ts file.
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react-swc';
import { VitePWA } from 'vite-plugin-pwa';

// https://vitejs.dev/config/
export default defineConfig({
plugins: [
react(),
VitePWA({
manifest: {
name: 'Vite-React-PWA-demo',
short_name: 'Vite-React-PWA',
description: 'PWA built with React and Vite',
start_url: '/',
display: 'standalone',
background_color: '#ffffff',
theme_color: '#000000',
icons: [
{
src: '/icons/logo48.png',
type: 'image/png',
sizes: '48x48',
},
{
src: '/icons/logo72.png',
type: 'image/png',
sizes: '72x72',
},
{
src: '/icons/logo96.png',
type: 'image/png',
sizes: '96x96',
},
{
src: '/icons/logo144.png',
type: 'image/png',
sizes: '144x144',
},
{
src: '/icons/logo192.png',
type: 'image/png',
sizes: '192x192',
},
{
src: '/icons/logo512.png',
type: 'image/png',
sizes: '512x512',
},
],
},
}),
],
});

Checkout the source code: https://github.com/Rutvi25/PWA-Demo/tree/pwa-vite-react-demo

Conclusion:

Progressive Web Apps (PWAs) bring a revolutionary paradigm to web development. Embracing this technology signifies a leap forward in creating web applications that are not just responsive but redefine the boundaries of user interactivity and accessibility by bridging the gap between web and native applications for a richer user experience.

However, the true magic lies in the intricate details — caching strategies ensuring swift load times, push notifications enhancing real-time engagement, and offline accessibility seamlessly weaving through connectivity gaps. As PWAs evolve, the commitment to refining these elements becomes paramount, ensuring that the user experience remains not only cutting-edge but consistently delightful.

For more updates on the latest tools and technologies, follow the Simform Engineering blog.

Follow Us: Twitter | LinkedIn

--

--