React useUnload Hook

ReactReactBeginner
Practice Now

This tutorial is from open-source community. Access the source code

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL react(("`React`")) -.-> react/FundamentalsGroup(["`Fundamentals`"]) react(("`React`")) -.-> react/AdvancedConceptsGroup(["`Advanced Concepts`"]) react/FundamentalsGroup -.-> react/jsx("`JSX`") react/AdvancedConceptsGroup -.-> react/hooks("`React Hooks`") subgraph Lab Skills react/jsx -.-> lab-38414{{"`React useUnload Hook`"}} react/hooks -.-> lab-38414{{"`React useUnload Hook`"}} end

React useUnload Hook

index.html and script.js have already been provided in the VM. In general, you only need to add code to script.js and style.css.

The beforeunload window event can be handled using the following steps:

  1. Create a ref for the callback function, fn, using the useRef() hook.
  2. Use the useEffect() hook and EventTarget.addEventListener() to handle the 'beforeunload' event, which is triggered when the user is about to close the window.
  3. 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.

Other React Tutorials you may like