Home/Blog/Web Development/How to build progressive web applications (PWA) with React
Home/Blog/Web Development/How to build progressive web applications (PWA) with React

How to build progressive web applications (PWA) with React

Zahid Irfan
Jan 16, 2024
2 min read

Become a Software Engineer in Months, Not Years

From your first line of code, to your first day on the job — Educative has you covered. Join 2M+ developers learning in-demand programming skills.

Progressive web apps (PWA) are web applications that allow features like platform-specific installation and offline access to function. The ability to install something like a desktop application enhances the user experience, and offline access allows us to work on the go without internet access. These look daunting to implement, but thanks to wonderful architectural design, programmers can build progressive web applications by setting variables in configuration files and a few application calls.

In this blog, we will learn how to build progressive web applications in React.

Simple PWA#

Now, let’s take a simple HTML/CSS application and convert it into a PWA.

Simple HTML/CSS application

Installation#

A manifest file is a JSON file that can be used to configure the PWA. The following manifest file can provide the basic parameters for the PWA:

{
"name": "Progressive Web Application",
"short_name": "PWA",
"description": "Use web application with the ease of native application. There is absolutely no need to install any software or packages.",
"start_url": "/",
"icons": [
{
"src": "icon-512.png",
"sizes": "512x512"
}
],
"theme_color": "#eeffee",
"background_color": "#eeffee",
"display": "standalone"
}

These are simple attributes of the application, like name, short name, description, start URL, theme/background color, and display mode. The display mode can be browser, standalone, minimal, or full screen.

A service worker allows network requests, cache management, and data store access. The service worker file sets up the progressive web application to launch a service worker. It contains the installation, fetch, and activate event handlers, which allow the programmer to manage the cache. Cache management is essential while the PWA is being installed, raising a fetch request, or being activated.

const VERSION = "v1";
const CACHE_NAME = `PWA-learner-${VERSION}`;
// Resources cached for offline access
const APP_STATIC_RESOURCES = [
'./index.html',
'./styles/css',
'icon-512.png'
];
// Installation Listener
self.addEventListener("install", (e) => {
e.waitUntil((async () => {
const cache = await caches.open("cacheName_identifier");
cache.addAll([
APP_STATIC_RESOURCES
]);
})()
);
});
// delete old caches on activate
self.addEventListener("activate", (event) => {
event.waitUntil(
(async () => {
const names = await caches.keys();
await Promise.all(
names.map((name) => {
if (name !== CACHE_NAME) {
return caches.delete(name);
}
})
);
await clients.claim();
})()
);
});
// On fetch, intercept server requests
// and respond with cached responses instead of going to network
self.addEventListener("fetch", (event) => {
// As a single page app, direct app to always go to cached home page.
if (event.request.mode === "navigate") {
event.respondWith(caches.match("/"));
return;
}
// For all other requests, go to the cache first, and then the network.
event.respondWith(
(async () => {
const cache = await caches.open(CACHE_NAME);
const cachedResponse = await cache.match(event.request.url);
if (cachedResponse) {
// Return the cached response if it's available.
return cachedResponse;
} else {
// If resource isn't in the cache, return a 404.
return new Response(null, { status: 404 });
}
})()
);
});

The HTML file needs to know about the manifest file and register the service worker. The manifest file is added as a link in line 2, and the service worker is registered in line 7.

<!-- Manifest file -->
<link rel="manifest" href="manifest.json" />
<!-- Resgister Service Worker (service_worker.js filename) -->
<script>
if ("serviceWorker" in navigator) {
navigator.serviceWorker.register("service_worker.js").then(
(registration) => {
console.log("Service worker registration successful:", registration);
},
(error) => {
console.error(`Service worker registration failed: ${error}`);
},
);
} else {
console.error("Service workers are not supported.");
}
</script>

This completes the PWA for a simple HTML/CSS web application.

Now, we will see how we can build a PWA using popular the React framework.

PWA with React#

React is the JavaScript library for building user interfaces. It comes with a lot of handy tools. One such tool is create-react-app, which can create boilerplate codes for React applications. It comes with a template for pwa and pwa-typescript to allow boilerplate code for PWA and TypeScript.

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

Also, there is a template for TypeScript:

npx create-react-app my-pwa-ts-app --template cra-template-pwa-typescript
  • This creates all required files for a React Progressive Web Application.

  • Essential files for PWA: manifest.json, service-worker.js, serviceWorkerRegistration.js.

  • File paths:public/manifest.json for the manifest file.src/service-worker.js for the service worker.src/serviceWorkerRegistration.js for service worker registration.

  • Necessary update in src/index.js: Change from unregister() to register().

  • This change activates the service worker, essential for PWA functionality.

// 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();

Creating a progressive web application is very simple using the create-react-app tool. However, it’s important to understand the underlying concepts to be able to customize the application. Check out the following course on Educative to learn more:

Zero to Hero with Progressive Web Applications

Cover
Optimize your web projects with Progressive Web Apps

Progressive Web Applications are the state of modern web solutions. With the proper strategies, it is possible to drastically improve the overall performance and providing data even without a network connection. In an increasingly mobile-first world, optimising the time to load web pages can be our business's success. We will start by describing what PWAs are and their advantages over native and plain web applications. We then go deeper analysing fundamental concepts like service workers, caching strategies and when to use them in different scenarios. Aside from generic, framework-agnostic code samples, there will be an entire "hands-on" section dedicated to Angular, where we will create a complete, real-world PWA project from scratch. Finally, we will learn how to deploy our PWAs to the cloud with different providers, describing in detail the approach with the Firebase platform. Thus, concluding our journey in the PWAs world.

5hrs
Beginner
5 Playgrounds
5 Quizzes

  

Free Resources