Handles the beforeunload
window event.
useRef()
hook to create a ref for the callback function, fn
.useEffect()
hook and EventTarget.addEventListener()
to handle the 'beforeunload'
(when the user is about to close the window).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'));
Would you like to help us improve 30 seconds of code?Take a quick survey
React, Hooks
Executes a callback whenever the window is scrolled.
React, Hooks
Executes a callback whenever the window is resized.
React, Hooks
Handles the event of clicking inside the wrapped component.