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