Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Change useScrollRestoration to use pagehide event #9945

Merged
merged 3 commits into from
Jan 24, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/small-squids-wash.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"react-router-dom": patch
---

Use `pagehide` instead of `beforeunload` for `<ScrollRestoration>`. This has better cross-browser support, specifically on Mobile Safari.
1 change: 1 addition & 0 deletions contributors.yml
Original file line number Diff line number Diff line change
Expand Up @@ -166,3 +166,4 @@
- xavier-lc
- xcsnowcity
- yuleicul
- jakkku
26 changes: 24 additions & 2 deletions packages/react-router-dom/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1143,8 +1143,8 @@ function useScrollRestoration({
};
}, []);

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

/**
* Setup a callback to be fired on the window's `pagehide` event. This is
* useful for saving some data to `window.localStorage` just before the page
* refreshes. This event is better supported than beforeunload across browsers.
*
* Note: The `callback` argument should be a function created with
* `React.useCallback()`.
*/
function usePageHide(
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not exported currently - but if this is indeed a better way to save off some data, maybe we should export it and make a note in the docs about the use-case difference between the two hooks?

callback: (event: PageTransitionEvent) => any,
options?: { capture?: boolean }
): void {
let { capture } = options || {};
React.useEffect(() => {
let opts = capture != null ? { capture } : undefined;
window.addEventListener("pagehide", callback, opts);
return () => {
window.removeEventListener("pagehide", callback, opts);
};
}, [callback, capture]);
}

/**
* Wrapper around useBlocker to show a window.confirm prompt to users instead
* of building a custom UI with useBlocker.
Expand Down