Ionic life cycle not working as expected when we create blank project for ionic-react

I tried to use react lifecycles both through Class component and function component but useIonViewWillLeave and useIonViewDidLeave is not fired when we create blank project in ionic react and navigate to another component using simple link or history.push methods.

I’m using @ionic/react version 5.0.7

import { IonContent, IonPage, useIonViewWillEnter, useIonViewDidEnter, useIonViewWillLeave, useIonViewDidLeave, IonItem, IonList, IonLabel, IonTabBar, IonTabButton, IonIcon} from '@ionic/react';
import React, {  FC } from 'react';
import { useHistory, Link } from 'react-router-dom';

const Vendor: FC = () => {
    const history = useHistory();
    const gotoHome = () => {
      history.push('/address')
    }
   useIonViewWillEnter(() =>{
     console.log('IonViewWillEnter - vendor');
   })
  
   useIonViewDidEnter(() => {
    console.log('IonViewDidEnter- vendor');
   });

   useIonViewWillLeave(() =>{
    console.log('IonViewWillLeave -vendor');
   });
  
   useIonViewDidLeave(()=>{
    console.log('IonViewDidLeave -vendor');
   });
   
    return (
  
      <IonPage>
         
        <IonContent fullscreen>
            vendor page

            <Link to="/address" className="btn btn-primary">got to home using link</Link>
            
            <h1 onClick ={gotoHome} >go to home</h1>
      </IonContent>
      </IonPage>
    );
  };
  
  export default Vendor;

and at the time of leaving the current page useIonViewDidEnter and useIonViewWillEnter triggered again.

I believe it is because the pages are still in the DOM. What are you trying to accomplish?

I’m fetching data from API in useIonViewWillEnter method but at the time of leaving this page that useIonViewWillEnter and useIonViewDidEnter executing again instead of useIonViewWillLeave and useIonViewDidLeave.

1 Like

I’m facing the exact same issue even today with Ionic 6.0.2

When navigating to a different route, instead of firing useIonViewWillLeave and useIonViewDidLeave, useIonViewWillEnter and useIonViewDidEnter are fired for the component/page which is being navigated away from.