I would like to detect when the user leaves the page Next JS. I count 3 ways of leaving a page:
Being able to detect when a page is leaved is very helpful for example, alerting the user some changes have not been saved yet.
I would like something like:
router.beforeLeavingPage(() => {
// my callback
})
I use 'next/router' like Next.js page to disconnect a socket
import { useEffect } from "react";
import { useRouter } from "next/router";
export default function MyPage() {
const router = useRouter();
useEffect(() => {
const exitingFunction = () => {
console.log("exiting...");
};
router.events.on("routeChangeStart", exitingFunction);
return () => {
console.log("unmounting component...");
router.events.off("routeChangeStart", exitingFunction);
};
}, []);
return <>My Page</>;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With