Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
09209b6
commit a5e45d7
Showing
2 changed files
with
43 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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 <>{/*... */}</>; | ||
} | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters