The smart way to get started with service workers is to use create-react-app, which provides a simple way to scaffold a basic service worker for a React app:
npx create-react-app hello-world --template cra-template-pwa
This quick start approach gives your site basic offline capabilities by adding two boilerplate js modules to the root of your project,
serviceWorkerRegistration.js. It also installs Google’s npm package workbox-sw that vastly simplifies everything about managing a service worker.
By the way, a couple of reference sources that I came across bear mentioning. First, the web site create-react-app.dev contains documentation that explains how to customize these two boiler plate files to optimize your site’s offline behavior. Additionally, if you’re just getting started with service workers then I’d recommend this blog post from Danielly Costa, “Showing ‘new version available’ notification on create-react-app PWAs“. It’s well-written, easy to follow, it’s relatively current as of this publication, and it’s what I used when I was just getting started.
Moving along, the boiler plate code adds the following to your React app: