Search code examples
reactjsreact-router-dom

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?


Solution

  • 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