Skip to content

Commit db73e94

Browse files
brophdawg11jakkku
andauthored
Change useScrollRestoration to use pagehide event (#9945)
Co-authored-by: Sungjin Kim <a01081440011@gmail.com>
1 parent 1787e40 commit db73e94

File tree

3 files changed

+30
-2
lines changed

3 files changed

+30
-2
lines changed

.changeset/small-squids-wash.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"react-router-dom": patch
3+
---
4+
5+
Use `pagehide` instead of `beforeunload` for `<ScrollRestoration>`. This has better cross-browser support, specifically on Mobile Safari.

contributors.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,3 +167,4 @@
167167
- xavier-lc
168168
- xcsnowcity
169169
- yuleicul
170+
- jakkku

packages/react-router-dom/index.tsx

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1143,8 +1143,8 @@ function useScrollRestoration({
11431143
};
11441144
}, []);
11451145

1146-
// Save positions on unload
1147-
useBeforeUnload(
1146+
// Save positions on pagehide
1147+
usePageHide(
11481148
React.useCallback(() => {
11491149
if (navigation.state === "idle") {
11501150
let key = (getKey ? getKey(location, matches) : null) || location.key;
@@ -1241,6 +1241,28 @@ export function useBeforeUnload(
12411241
}, [callback, capture]);
12421242
}
12431243

1244+
/**
1245+
* Setup a callback to be fired on the window's `pagehide` event. This is
1246+
* useful for saving some data to `window.localStorage` just before the page
1247+
* refreshes. This event is better supported than beforeunload across browsers.
1248+
*
1249+
* Note: The `callback` argument should be a function created with
1250+
* `React.useCallback()`.
1251+
*/
1252+
function usePageHide(
1253+
callback: (event: PageTransitionEvent) => any,
1254+
options?: { capture?: boolean }
1255+
): void {
1256+
let { capture } = options || {};
1257+
React.useEffect(() => {
1258+
let opts = capture != null ? { capture } : undefined;
1259+
window.addEventListener("pagehide", callback, opts);
1260+
return () => {
1261+
window.removeEventListener("pagehide", callback, opts);
1262+
};
1263+
}, [callback, capture]);
1264+
}
1265+
12441266
/**
12451267
* Wrapper around useBlocker to show a window.confirm prompt to users instead
12461268
* of building a custom UI with useBlocker.

0 commit comments

Comments
 (0)