Published on

usePageleave Hook React

usePageleave Hook React

usePageleave Hook React

usePageleave Code and Usage

usePageleave is a hook to detect when the user leaves the page

import { useEffect } from "react";

const usePageLeave = (callback) => {
  useEffect(() => {
    const handlePageLeave = (event) => {
      if (typeof callback === "function") {
        callback();
      }
    };

    window.addEventListener("beforeunload", handlePageLeave);

    return () => {
      window.removeEventListener("beforeunload", handlePageLeave);
    };
  }, [callback]);
};

// Usage
const PageLeaveExample = () => {
  usePageLeave(() => {
    console.log("Leaving the page...");
  });

  return (
    <div>
      <p>Try closing or refreshing the page.</p>
    </div>
  );
};