ionViewWillEnter vs ionViewDidEnter

sebaferreras answer is great but it is missing some points.

First, about ionic life cycle. If you write down all ionic events and put a console.log in each, you will see the scenario:

constructor --> ionViewDidLoad --> ionViewWillEnter --> ionViewDidEnter --> ionViewWillLeave --> ionViewDidLeave --> ionViewWillUnload.

constructor run first when the page is initiated. This is the best place for you to declare default values for your variables.
ionViewDidLoad is fired when the view is completely loaded. It means you can attach DOM element here.

ionViewWillEnter runs when the page is about to enter and become the active page.
ionViewDidEnter runs when the page has fully entered and is now the active page.
ionViewDidEnter will fire after all synchronous in ionViewWillEnter completed. To prove it, just put heavy code into ionViewWillEnter:

ionViewWillEnter(){
    console.log("ionViewWillEnter")
    for(let i = 0; i < 100000; i++){
      console.log(i);
    }
}
ionViewDidEnter(){
    console.log("ionViewDidEnter")
}

Run your code and you will see it take so long time to launch your page. So never put heavy synchronous code into ionViewWillEnter. Just use asynchronous in ionViewWillEnter and move all synchronous code to ionViewDidEnter. Because in there, your page is entered and it will make a better UX.

Leave a Comment