All hooks / Page, device, and user
usePageRestore
Calls callback when the browser restores the page from its back/forward cache, e.g. the user comes back with the Back button. The page reappears exactly as it was left: no reload, no new render, no effects re-run, so data shown on it may be stale.
Always calls the latest callback. Nothing runs on the server or on a normal page load.
Import
import { usePageRestore } from '@vincent.ri/react-tils'
// or only this hook
import { usePageRestore } from '@vincent.ri/react-tils/usePageRestore'Usage
const { data, refetch } = useCart() // your data-fetching hook
usePageRestore(() => refetch())
// Reset a form that was left mid-submit before navigating away.
usePageRestore(() => setSubmitting(false))Live demo
Open another page in this tab, then press Back.
When to use it
Refreshing a cart, notifications, prices, or anything else that may have changed while the user was on another page, or resetting UI such as an open menu or a "Submitting…" button left over from before.
When not to
You want to know when the tab becomes visible again; use useDocumentVisibility. Avoid unload listeners anywhere on the page: they stop browsers from caching it at all.
API
function usePageRestore(callback: (event: PageTransitionEvent) => void): void| Parameter | Description |
|---|---|
callback | Called with the pageshow event. Can change every render. |
Browser support
| Uses | Chrome | Edge | Firefox | Safari | Chrome Android | Safari iOS |
|---|---|---|---|---|---|---|
| pageshow eventWidely available | 3+ | 12+ | 6+ | 5+ | 18+ | 4.2+ |
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 useBfcache, usePageShow.