useUnsavedChanges
Ask before leaving a page with a form that is not saved.
const { blocked, proceed, stay } = useUnsavedChanges({ when, links = true })Protects a form with changes that were not saved or submitted. While when is true, closing or reloading the tab shows the browser's own "Leave site?" prompt, and a click on a link to another page of your app is held back: blocked turns true, you show your own "Discard changes?" dialog, and call proceed() to go on to that link or stay() to drop the click. It works with plain links and router links alike. Set when back to false as soon as the form is saved or submitted.
It does not see navigation that is not a link click (the browser back button, navigate() in code): use your router's own blocker for those. For the browser prompt alone, useLeaveWarning is enough.
API
Parameters
whenbooleanTrue while the form has unsaved changes.
linksbooleanDefault:trueAlso hold back clicks on links to other pages, so you can ask first.
| Prop | Type | Default | Description |
|---|---|---|---|
when | boolean | – | True while the form has unsaved changes. |
links | boolean | true | Also hold back clicks on links to other pages, so you can ask first. |
Returns
blockedbooleanA link click is waiting for an answer: show your dialog.
proceed() => voidLeave: follows the link that was clicked, without asking again.
stay() => voidStay: drops the held-back click.
| Prop | Type | Default | Description |
|---|---|---|---|
blocked | boolean | – | A link click is waiting for an answer: show your dialog. |
proceed | () => void | – | Leave: follows the link that was clicked, without asking again. |
stay | () => void | – | Stay: drops the held-back click. |