DEV Community

Discussion on: Creating Custom React Hooks: useConfirmTabClose

Collapse
 
wparad profile image
Warren Parad • Edited

Unfortunately this is terrible advice. You should never stop the user from leaving the page, this is one of the most annoying things you that you can do to them. Additionally most browsers don't even let you do this:

Event disabled

Lastly, the event while supported is totally unreliable, the user may leave the page because of any number of reasons:

  • They want to
  • They shut down their browser
  • They are locking it or turning it off.

You'll never get the event in these cases. The only right thing to do is to always persist the state to localstorage, and in some cases to your service for syncing purposes. You can store drafts of important changes automatically. There's no reason you should ever stop the user from leaving your page.

Collapse
 
jedgrant profile image
Jed Grant

Warren, I disagree with your assertion about this being terrible advice and that you should "never" stop them from leaving the page. If you have a long form, or any user entered data, and the user intends to save it, but does not for any reason, putting it in localStorage doesn't solve the problem. The user has no idea they didn't save or submit. Taking steps to help them realize what happening, is helpful.

Yes, there's lots of places this is abused and it's irritating, but any form that takes time to fill out, or even small forms with lots of text, benefit from checking with the user to try to help them avoid data loss/wasted time.

Thanks for the article Zach!