Detect when a user leaves the page (app/ dir)
Unanswered
Masai Lion posted this in #help-forum
Masai LionOP
Hello, I need to detect when a page changes in Nextjs 13 / app directory.
I've tried this, but it doesnt work :
It displays the console.log() when the page loads, but not when it unloads
I've tried this, but it doesnt work :
const pathname = usePathname()
const [previousPathname, setPreviousPathname] = useState<string|null>(null);
useEffect(()=>{
if(previousPathname && (previousPathname != pathname)){
console.log("page changed")
setPreviousPathname(null)
}else{
console.log("page didnt change")
setPreviousPathname(pathname)
}
}
}, [pathname])It displays the console.log() when the page loads, but not when it unloads
2 Replies
Masai LionOP
Solved ! Simply as that :
useEffect(() => {
return () => {
console.log("unmounting component...");
};
}, []);Northeast Congo Lion
Please, Can a prompt be made to confirm if he wants to leave the page with this approach ?