Skip to content

Latest commit

 

History

History
49 lines (37 loc) · 1.16 KB

useBeforeUnload.md

File metadata and controls

49 lines (37 loc) · 1.16 KB

useBeforeUnload

React side-effect hook that shows browser alert when user try to reload or close the page.

Usage

Boolean check

import {useBeforeUnload} from 'react-use';

const Demo = () => {
  const [dirty, toggleDirty] = useToggle(false);
  useBeforeUnload(dirty, 'You have unsaved changes, are you sure?');

  return (
    <div>
      {dirty && <p>Try to reload or close tab</p>}
      <button onClick={() => toggleDirty()}>{dirty ? 'Disable' : 'Enable'}</button>
    </div>
  );
};

Function check

Note: Since every dirtyFn change registers a new callback, you should use refs if your test value changes often.

import {useBeforeUnload} from 'react-use';

const Demo = () => {
  const [dirty, toggleDirty] = useToggle(false);
  const dirtyFn = useCallback(() => {
    return dirty;
  }, [dirty]);
  useBeforeUnload(dirtyFn, 'You have unsaved changes, are you sure?');

  return (
    <div>
      {dirty && <p>Try to reload or close tab</p>}
      <button onClick={() => toggleDirty()}>{dirty ? 'Disable' : 'Enable'}</button>
    </div>
  );
};