Menu

gitpiper

useUnload react Code Snippet in 2022

hookseffecteventintermediate

Last Updated: 27 September 2022

Handles the beforeunload window event.

  • Use the useRef() hook to create a ref for the callback function, fn.
  • Use the useEffect() hook and EventTarget.addEventListener() to handle the 'beforeunload' (when the user is about to close the window).
  • Use EventTarget.removeEventListener() to perform cleanup after the component is unmounted.
const useUnload = fn => { const cb = React.useRef(fn); React.useEffect(() => { const onUnload = cb.current; window.addEventListener('beforeunload', onUnload); return () => { window.removeEventListener('beforeunload', onUnload); }; }, [cb]); };
const App = () => { useUnload(e => { e.preventDefault(); const exit = confirm('Are you sure you want to leave?'); if (exit) window.close(); }); return <div>Try closing the window.</div>; }; ReactDOM.render(<App />, document.getElementById('root'));

react snippet similar to useUnload For You in September 2022

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️

© 2022 GitPiper. All rights reserved

Rackpiper Technology Inc

Company

About UsBlogContact

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️