All hooks / Browser APIs
useServiceWorkerUpdate
Whether a new version of your service worker (a PWA's offline code) is installed and waiting, and update() to switch to it and reload once.
Notices a worker that was already waiting when the page loaded, and one that finishes installing while the page is open. update() tells the waiting worker to take over, then reloads the page exactly once when it has, never in a loop. Nothing happens on the server or without a service worker.
Your service worker must call self.skipWaiting() when it receives the message { type: 'SKIP_WAITING' }. Workbox and vite-plugin-pwa do this with their "prompt for update" setting.
Import
import { useServiceWorkerUpdate } from '@vincent.ri/react-tils'
// or only this hook
import { useServiceWorkerUpdate } from '@vincent.ri/react-tils/useServiceWorkerUpdate'Usage
const { updateAvailable, update } = useServiceWorkerUpdate({ checkIntervalMs: 60 * 60_000 })
if (!updateAvailable) return null
return (
<div role="status">
A new version is available. <button onClick={update}>Reload</button>
</div>
)Live demo
This demo has no service worker, so there is never an update.
When to use it
Showing a "New version available. Reload" banner in a PWA or any site with a service worker.
When not to
You don't use a service worker; a deploy then reaches users on their next page load anyway. To check whether the user is online, use useOnline.
API
function useServiceWorkerUpdate(options?: ServiceWorkerUpdateOptions): {
updateAvailable: boolean;
update: () => void;
}| Parameter | Description |
|---|---|
options | checkIntervalMs. Optional. |
Returns { updateAvailable, update }.
Types
export type ServiceWorkerUpdateOptions = {
/** Also ask the server for a new service worker this often, in milliseconds. Default: only when the browser checks by itself (on navigation). */
checkIntervalMs?: number;
};Browser support
| Uses | Chrome | Edge | Firefox | Safari | Chrome Android | Safari iOS |
|---|---|---|---|---|---|---|
| Service workersWidely available | 40+ | 17+ | 44+ | 11.1+ | 40+ | 11.3+ |
- Service workers need a secure page (HTTPS or localhost).
First version with support, from MDN's compatibility data (web-features 3.42.0, @mdn/browser-compat-data 8.1.5).
Coming from another library?
Other libraries call this useRegisterSW (vite-plugin-pwa), useServiceWorker.