Introduction
In this lab, we will explore the useUnload hook in React, which allows us to handle the beforeunload window event. The purpose of this lab is to demonstrate how to use this hook to create a callback function that will be triggered when the user tries to close the window. We will also learn how to perform cleanup after the component is unmounted. By the end of this lab, you will have a better understanding of how to manage window events in React.
React useUnload Hook
index.htmlandscript.jshave already been provided in the VM. In general, you only need to add code toscript.jsandstyle.css.
The beforeunload window event can be handled using the following steps:
- Create a ref for the callback function,
fn, using theuseRef()hook. - Use the
useEffect()hook andEventTarget.addEventListener()to handle the'beforeunload'event, which is triggered when the user is about to close the window. - Use
EventTarget.removeEventListener()to perform cleanup after the component is unmounted.
Here's the code:
const useUnload = (fn) => {
const callbackRef = React.useRef(fn);
React.useEffect(() => {
const callback = callbackRef.current;
window.addEventListener("beforeunload", callback);
return () => {
window.removeEventListener("beforeunload", callback);
};
}, [callbackRef]);
};
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.createRoot(document.getElementById("root")).render(<App />);
Please click on 'Go Live' in the bottom right corner to run the web service on port 8080. Then, you can refresh the Web 8080 Tab to preview the web page.
Summary
Congratulations! You have completed the React useUnload Hook lab. You can practice more labs in LabEx to improve your skills.