# 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

```ts
import { useServiceWorkerUpdate } from '@vincent.ri/react-tils'
// or only this hook
import { useServiceWorkerUpdate } from '@vincent.ri/react-tils/useServiceWorkerUpdate'
```

## Usage

```ts
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>
)
```

## 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

```ts
function useServiceWorkerUpdate(options?: ServiceWorkerUpdateOptions): {
  updateAvailable: boolean;
  update: () => void;
}
```

| Parameter | Description |
| --- | --- |
| `options` | `checkIntervalMs`. Optional. |

**Returns** `{ updateAvailable, update }`.

### Types

```ts
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

Works in all modern browsers.

- Service workers need a secure page (HTTPS or localhost).

## Coming from another library?

Other libraries call this `useRegisterSW` (vite-plugin-pwa), `useServiceWorker`.

---

418 B minified and brotlied
Source: https://github.com/vincentri/react-tils/blob/main/src/useServiceWorkerUpdate.ts
Docs page: https://vincentri.github.io/react-tils/hooks/useServiceWorkerUpdate/
Previous: [useScript](https://vincentri.github.io/react-tils/hooks/useScript.md)
Next: [useScrollLock](https://vincentri.github.io/react-tils/hooks/useScrollLock.md)
