Skip to content

Commit

Permalink
Export useBeforeUnload
Browse files Browse the repository at this point in the history
  • Loading branch information
brophdawg11 committed Dec 12, 2022
1 parent 09209b6 commit a5e45d7
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 2 deletions.
32 changes: 32 additions & 0 deletions docs/hooks/use-before-unload.md
@@ -0,0 +1,32 @@
---
title: useBeforeUnload
new: true
---

# `useBeforeUnload`

This hook is just a helper around `window.onbeforeunload`. It can be useful to save important application state on the page (to something like the browser's local storage), before the user navigates away from your page. That way if they come back you can restore any stateful information (restore form input values, etc.)

```tsx lines=[1,7-11]
import { useBeforeUnload } from "react-router-dom";

function SomeForm() {
const [state, setState] = React.useState(null);

// save it off before users navigate away
useBeforeUnload(
React.useCallback(() => {
localStorage.stuff = state;
}, [state])
);

// read it in when they return
React.useEffect(() => {
if (state === null && localStorage.stuff != null) {
setState(localStorage.stuff);
}
}, [state]);

return <>{/*... */}</>;
}
```
13 changes: 11 additions & 2 deletions packages/react-router-dom/index.tsx
Expand Up @@ -1179,15 +1179,24 @@ function useScrollRestoration({
}, [location, restoreScrollPosition, preventScrollReset, skip]);
}

function useBeforeUnload(callback: () => any): void {
/**
* Setup a callback to be fired on the window's `beforeunload` event. This is
* useful for saving some data to `window.localStorage` just before the page
* refreshes.
*
* Note: The `callback` argument should be a function created with
* `React.useCallback()`.
*/
export function useBeforeUnload(
callback: (event: BeforeUnloadEvent) => any
): void {
React.useEffect(() => {
window.addEventListener("beforeunload", callback);
return () => {
window.removeEventListener("beforeunload", callback);
};
}, [callback]);
}

//#endregion

////////////////////////////////////////////////////////////////////////////////
Expand Down

0 comments on commit a5e45d7

Please sign in to comment.