MBŠ
MBŠ

Reputation: 397

React Router Dom v6 Detect user is leaving a page and do something

When a user is leaving a page or goes to another route, I want a dispatch to happen. Here's some pseudocode:

useEffect(()=>{
  if(userLeave){
     dispatch(clearData())
  }
},[userLeave])

Is there a good example of how to create such a dispatch when a user leaves the page or goes to another route?

Upvotes: 2

Views: 6264

Answers (1)

Ali Sattarzadeh
Ali Sattarzadeh

Reputation: 3549

try this in Component where your route renders:

useEffect(()=>{
   return ()=> dispatch(clearData())
},[])

for example, you have a '/home' pathname and you are rendering Home Component:

const  Home = ()=> {

useEffect(()=>{
    return ()=> dispatch(clearData())
},[])

return (
    <div>
        Hello
    </div>
);

}

export default Home;

return in useEffect acts like componentDidUnmount you can use it for your purpose

Upvotes: 0

Related Questions