Skip to content

Commit 423801f

Browse files
committed
feat: smoother updates with reloadWhenHidden, canReload and non-blocking mount
- Check at once when a tab gets focus back after a whole `duration`, instead of waiting another interval on a stale build. - `reloadWhenHidden` reloads into a newer build as soon as the tab goes to the background, so users never see the switch. - `canReload` is asked before every reload the user did not start (`auto`, `reloadWhenHidden`); a throwing guard counts as a no. - `blocking={false}` renders the app at once and checks in the background. The demo gains controls for the new options, and the README documents them with a reload-on-navigation recipe.
1 parent e17cdd5 commit 423801f

4 files changed

Lines changed: 386 additions & 27 deletions

File tree

‎README.md‎

Lines changed: 44 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,8 @@ Users leave tabs open for days. After you deploy, those tabs still run the old b
2121

2222
- **Detects new builds** by polling a tiny `meta.json` that a CLI writes at build time.
2323
- **Recovers from stale-chunk errors** — webpack and Vite chunk failures, native `import()` errors in Chrome, Firefox and Safari, and HTML served in place of a script — and passes every other error on to your own error boundary.
24-
- **Asks or acts:** reload on its own, or show an accessible update prompt (built in, or your own component).
24+
- **Asks or acts:** reload on its own, quietly while the tab is in the background, or show an accessible update prompt (built in, or your own component). A `canReload` guard protects unsaved work.
25+
- **Checks when users return:** a tab that was in the background for a while checks for a new build as soon as it gets focus.
2526
- **Clears Cache Storage** before reloading, so a service worker cannot serve the old build again.
2627
- **`lazyRetry`** for flaky networks: retries a dynamic import before giving up.
2728
- **Small and typed:** React 18 and 19, ESM and CommonJS, TypeScript declarations, no runtime dependencies.
@@ -93,7 +94,15 @@ createRoot(document.getElementById('root')!).render(
9394

9495
**3. Deploy.** Tabs with the old build now see a prompt within a minute, or as soon as a lazy chunk fails to load.
9596

96-
Prefer silent reloads? Drop `updatePrompt` and set `auto`.
97+
Prefer no prompt at all? Set `reloadWhenHidden`: the tab reloads into the new build the moment the user switches away from it. Add `canReload` to hold off while a form has unsaved changes.
98+
99+
```tsx
100+
<ClearBrowserCacheBoundary
101+
duration={60_000}
102+
reloadWhenHidden
103+
canReload={() => !formIsDirty()}
104+
>
105+
```
97106

98107
## How it works
99108

@@ -113,8 +122,9 @@ flowchart LR
113122
I -- no --> K[rethrow to your ErrorBoundary]
114123
```
115124
116-
- On mount the boundary shows `fallback` and fetches the meta file. A newer build found on mount always reloads straight away, since nothing has been shown yet.
117-
- Polling runs every `duration` ms, only while the window has focus. When it finds a newer build it reloads if `auto` is set; otherwise it shows `updatePrompt`, or just sets `isLatestVersion` to `false` and leaves the reload to you (`clearCacheAndReload`).
125+
- On mount the boundary shows `fallback` and fetches the meta file; with `blocking={false}` it renders the app at once and checks in the background. A newer build found on mount always reloads straight away.
126+
- Polling runs every `duration` ms, only while the window has focus. A tab that gets focus back after a whole `duration` checks at once. When a check finds a newer build it reloads if `auto` is set; otherwise it shows `updatePrompt`, or just sets `isLatestVersion` to `false` and leaves the reload to you (`clearCacheAndReload`).
127+
- With `reloadWhenHidden`, a tab that knows about a newer build reloads as soon as it goes to the background. `canReload` is asked before this reload and before every `auto` reload; a reload the user clicks is never blocked.
118128
- When a child throws an error that looks like a stale build, the boundary checks the version: if a new build is out it reloads (or prompts, with `promptOnError`); otherwise the error goes on to your `ErrorBoundary`.
119129
- The meta file is fetched with `cache: 'no-store'`. A file that is missing, has no `version`, or is answered with HTML by an SPA fallback is reported to `debug` and otherwise ignored; the app still renders.
120130
- If storage cannot be read (blocked cookies, private mode), the boundary disables itself and just renders the app.
@@ -174,18 +184,21 @@ A plain element works too (`updatePrompt={<Banner />}`); it reads `clearCacheAnd
174184
175185
Error boundary and context provider. Place it inside your own error boundary: it only handles stale-build errors.
176186
177-
| Prop | Type | Default | Description |
178-
| :-------------- | :------------------------------ | :-------------- | :------------------------------------------------------------------------------------------------------------------------------------ |
179-
| `duration` | `number` | — | Poll interval in ms. Without it the version is checked on mount and on stale-chunk errors only. |
180-
| `auto` | `boolean` | `false` | Reload as soon as a poll finds a newer build. |
181-
| `fallback` | `ReactNode` | `null` | Rendered while the first version check runs, e.g. a preloader. |
182-
| `updatePrompt` | element or component | — | Shown when a newer build is found and the page is not reloaded on its own. See [Update prompt](#update-prompt). |
183-
| `promptOnError` | `boolean` | `false` | On a stale-build error, show `updatePrompt` over `fallback` instead of reloading at once. |
184-
| `filename` | `string` | `'meta.json'` | Meta file to fetch. A bare name is fetched from the site root; a path starting with `/`, `./` or `../`, or a full URL, is used as is. |
185-
| `storageKey` | `string` | `'APP_VERSION'` | Key the current version is stored under. |
186-
| `storage` | `{ get(key), set(key, value) }` | `localStorage` | Where the version is kept, e.g. [store](https://www.npmjs.com/package/store). |
187-
| `errorCheckers` | `((error) => boolean)[]` | `[]` | Extra checks for stale-build errors, added to the defaults. See [`createErrorChecker`](#createerrorcheckername-pattern). |
188-
| `debug` | `(params) => void` | — | Receives state changes and errors, for logging. |
187+
| Prop | Type | Default | Description |
188+
| :----------------- | :------------------------------ | :-------------- | :------------------------------------------------------------------------------------------------------------------------------------ |
189+
| `duration` | `number` | — | Poll interval in ms. Without it the version is checked on mount and on stale-chunk errors only. |
190+
| `auto` | `boolean` | `false` | Reload as soon as a poll finds a newer build. |
191+
| `fallback` | `ReactNode` | `null` | Rendered while the first version check runs, e.g. a preloader. |
192+
| `updatePrompt` | element or component | — | Shown when a newer build is found and the page is not reloaded on its own. See [Update prompt](#update-prompt). |
193+
| `promptOnError` | `boolean` | `false` | On a stale-build error, show `updatePrompt` over `fallback` instead of reloading at once. |
194+
| `reloadWhenHidden` | `boolean` | `false` | Reload into a newer build as soon as the tab goes to the background. |
195+
| `canReload` | `() => boolean` | — | Asked before reloads the user did not start (`auto`, `reloadWhenHidden`). Return `false` to keep the page. |
196+
| `blocking` | `boolean` | `true` | Show `fallback` until the first check answers. `false` renders the app at once. |
197+
| `filename` | `string` | `'meta.json'` | Meta file to fetch. A bare name is fetched from the site root; a path starting with `/`, `./` or `../`, or a full URL, is used as is. |
198+
| `storageKey` | `string` | `'APP_VERSION'` | Key the current version is stored under. |
199+
| `storage` | `{ get(key), set(key, value) }` | `localStorage` | Where the version is kept, e.g. [store](https://www.npmjs.com/package/store). |
200+
| `errorCheckers` | `((error) => boolean)[]` | `[]` | Extra checks for stale-build errors, added to the defaults. See [`createErrorChecker`](#createerrorcheckername-pattern). |
201+
| `debug` | `(params) => void` | — | Receives state changes and errors, for logging. |
189202
190203
### `useClearBrowserCache()` and `<ClearBrowserCache>`
191204
@@ -266,6 +279,21 @@ Recognised out of the box: webpack `ChunkLoadError` and CSS chunk errors, Vite C
266279

267280
**Version from your CI instead of a random UUID.** Any JSON with a `version` string works, e.g. `echo "{\"version\":\"$GITHUB_SHA\"}" > public/meta.json`.
268281
282+
**Reload on the next route change.** A route change replaces the screen anyway, so it is a quiet moment to switch builds:
283+
284+
```tsx
285+
function ReloadOnNavigate() {
286+
const { isLatestVersion, clearCacheAndReload } = useClearBrowserCache();
287+
const location = useLocation(); // react-router
288+
289+
useEffect(() => {
290+
if (!isLatestVersion) clearCacheAndReload();
291+
}, [location.pathname]);
292+
293+
return null;
294+
}
295+
```
296+
269297
**Show the update somewhere other than a dialog.** Leave `updatePrompt` out and render a banner from `isLatestVersion` with the hook.
270298
271299
## Troubleshooting

‎example/src/demo/Demo.tsx‎

Lines changed: 32 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,8 @@ type Settings = {
3939
duration: number;
4040
prompt: PromptChoice;
4141
promptOnError: boolean;
42+
reloadWhenHidden: boolean;
43+
blocking: boolean;
4244
};
4345

4446
const durations = [
@@ -56,7 +58,9 @@ function readSettings(): Settings {
5658
auto: params.get('auto') === '1',
5759
duration: durations.some((d) => d.value === duration) ? duration : 3000,
5860
prompt: prompt === 'banner' || prompt === 'none' ? prompt : 'dialog',
59-
promptOnError: params.get('promptOnError') !== '0'
61+
promptOnError: params.get('promptOnError') !== '0',
62+
reloadWhenHidden: params.get('reloadWhenHidden') === '1',
63+
blocking: params.get('blocking') !== '0'
6064
};
6165
}
6266

@@ -66,7 +70,9 @@ function writeSettings(settings: Settings) {
6670
auto: settings.auto ? '1' : '0',
6771
duration: String(settings.duration),
6872
prompt: settings.prompt,
69-
promptOnError: settings.promptOnError ? '1' : '0'
73+
promptOnError: settings.promptOnError ? '1' : '0',
74+
reloadWhenHidden: settings.reloadWhenHidden ? '1' : '0',
75+
blocking: settings.blocking ? '1' : '0'
7076
});
7177
history.replaceState(null, '', `?${params}`);
7278
}
@@ -256,6 +262,24 @@ function Settings({
256262
<code>auto</code>
257263
<small>reload as soon as a poll finds a new build</small>
258264
</label>
265+
<label className='check'>
266+
<input
267+
type='checkbox'
268+
checked={settings.reloadWhenHidden}
269+
onChange={(e) => set({ reloadWhenHidden: e.target.checked })}
270+
/>
271+
<code>reloadWhenHidden</code>
272+
<small>reload quietly when you switch to another tab</small>
273+
</label>
274+
<label className='check'>
275+
<input
276+
type='checkbox'
277+
checked={!settings.blocking}
278+
onChange={(e) => set({ blocking: !e.target.checked })}
279+
/>
280+
<code>blocking={'{false}'}</code>
281+
<small>show the app before the first check answers</small>
282+
</label>
259283
</fieldset>
260284
);
261285
}
@@ -265,6 +289,8 @@ function snippet(settings: Settings) {
265289
"filename='/react-clear-browser-cache/meta.json'",
266290
settings.duration ? `duration={${settings.duration}}` : null,
267291
settings.auto ? 'auto' : null,
292+
settings.reloadWhenHidden ? 'reloadWhenHidden' : null,
293+
settings.blocking ? null : 'blocking={false}',
268294
settings.prompt === 'dialog' ? 'updatePrompt={UpdatePrompt}' : null,
269295
settings.prompt === 'banner' ? 'updatePrompt={MyBanner}' : null,
270296
settings.prompt !== 'none' && settings.promptOnError
@@ -366,8 +392,8 @@ export default function Demo() {
366392
<code>{snippet(settings)}</code>
367393
</pre>
368394
<p className='note'>
369-
Polling pauses while this tab is in the background and restarts when
370-
it gets focus.
395+
Polling pauses while this tab is in the background. When it gets
396+
focus back after a whole interval, it checks at once.
371397
</p>
372398
</section>
373399

@@ -380,6 +406,8 @@ export default function Demo() {
380406
duration={settings.duration || undefined}
381407
updatePrompt={prompts[settings.prompt]}
382408
promptOnError={settings.promptOnError}
409+
reloadWhenHidden={settings.reloadWhenHidden}
410+
blocking={settings.blocking}
383411
filename={`${import.meta.env.BASE_URL}meta.json`}
384412
debug={debug}
385413
>

‎src/ClearBrowserCacheBoundary.tsx‎

Lines changed: 72 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,22 @@ export type ClearBrowserCacheBoundaryProps = React.PropsWithChildren<{
4444
* instead of reloading straight away.
4545
*/
4646
promptOnError?: boolean;
47+
/**
48+
* Reload into a newer build as soon as the tab goes to the background,
49+
* where the user cannot see it happen.
50+
*/
51+
reloadWhenHidden?: boolean;
52+
/**
53+
* Asked before every reload the user did not start (`auto`,
54+
* `reloadWhenHidden`); return false to keep the page, e.g. while a form has
55+
* unsaved changes.
56+
*/
57+
canReload?: () => boolean;
58+
/**
59+
* Show `fallback` until the first version check answers. Off renders the
60+
* app at once and checks in the background.
61+
*/
62+
blocking?: boolean;
4763
}>;
4864

4965
export type ClearBrowserCacheContextValue = ClearBrowserCacheBoundaryState & {
@@ -120,6 +136,7 @@ export class ClearBrowserCacheBoundary extends React.Component<
120136
// successful check on this device.
121137
appVersion: string | null;
122138
checkInterval: ReturnType<typeof setInterval> | null = null;
139+
lastCheckAt = 0;
123140
unmounted = false;
124141

125142
constructor(props: ClearBrowserCacheBoundaryProps) {
@@ -168,8 +185,9 @@ export class ClearBrowserCacheBoundary extends React.Component<
168185
componentDidMount() {
169186
// StrictMode unmounts and remounts the same instance in development.
170187
this.unmounted = false;
171-
window.addEventListener('focus', this.startVersionCheck);
188+
window.addEventListener('focus', this.handleFocus);
172189
window.addEventListener('blur', this.stopVersionCheck);
190+
document.addEventListener('visibilitychange', this.handleVisibilityChange);
173191

174192
// Nothing has been shown yet, so a stale build is reloaded on mount even
175193
// without `auto`.
@@ -200,8 +218,12 @@ export class ClearBrowserCacheBoundary extends React.Component<
200218
this.unmounted = true;
201219
this.stopVersionCheck();
202220

203-
window.removeEventListener('focus', this.startVersionCheck);
221+
window.removeEventListener('focus', this.handleFocus);
204222
window.removeEventListener('blur', this.stopVersionCheck);
223+
document.removeEventListener(
224+
'visibilitychange',
225+
this.handleVisibilityChange
226+
);
205227
}
206228

207229
componentDidCatch(error: unknown, errorInfo: React.ErrorInfo) {
@@ -259,14 +281,55 @@ export class ClearBrowserCacheBoundary extends React.Component<
259281
}
260282
};
261283

284+
// Polling stops while the window is in the background, so a tab left alone
285+
// for hours would otherwise wait a whole `duration` after coming back.
286+
handleFocus = () => {
287+
const { duration } = this.props;
288+
289+
if (
290+
!this.state.disabled &&
291+
duration &&
292+
Date.now() - this.lastCheckAt >= duration
293+
) {
294+
this.checkVersion();
295+
}
296+
297+
this.startVersionCheck();
298+
};
299+
300+
handleVisibilityChange = () => {
301+
const { loading, isLatestVersion, caughtError, disabled } = this.state;
302+
303+
if (
304+
document.visibilityState === 'hidden' &&
305+
this.props.reloadWhenHidden &&
306+
!disabled &&
307+
!loading &&
308+
!isLatestVersion &&
309+
!caughtError &&
310+
this.reloadAllowed()
311+
) {
312+
this.clearCacheAndReload();
313+
}
314+
};
315+
316+
reloadAllowed() {
317+
try {
318+
return this.props.canReload?.() ?? true;
319+
} catch (error) {
320+
this.debug(error);
321+
return false;
322+
}
323+
}
324+
262325
startVersionCheck = () => {
263-
const { duration, auto = false } = this.props;
326+
const { duration } = this.props;
264327

265328
this.stopVersionCheck();
266329

267330
if (!this.state.disabled && duration) {
268331
this.checkInterval = setInterval(() => {
269-
this.checkVersion({ auto });
332+
this.checkVersion();
270333
}, duration);
271334
}
272335
};
@@ -327,8 +390,10 @@ export class ClearBrowserCacheBoundary extends React.Component<
327390
}
328391

329392
checkVersion = async ({
330-
auto = this.props.auto ?? false
393+
auto = (this.props.auto ?? false) && this.reloadAllowed()
331394
} = {}): Promise<CheckResult> => {
395+
this.lastCheckAt = Date.now();
396+
332397
try {
333398
const latestVersion = await this.fetchLatestVersion();
334399

@@ -404,7 +469,7 @@ export class ClearBrowserCacheBoundary extends React.Component<
404469
}
405470

406471
render() {
407-
const { children, fallback = null } = this.props;
472+
const { children, fallback = null, blocking = true } = this.props;
408473
const { caughtError, loading, isLatestVersion, latestVersion, disabled } =
409474
this.state;
410475

@@ -423,7 +488,7 @@ export class ClearBrowserCacheBoundary extends React.Component<
423488
dismissUpdate: this.dismissUpdate
424489
}}
425490
>
426-
{caughtError || loading ? fallback : children}
491+
{caughtError || (loading && blocking) ? fallback : children}
427492
{this.renderUpdatePrompt()}
428493
</ClearBrowserCacheCtx.Provider>
429494
);

0 commit comments

Comments
 (0)