ionViewWillEnter vs ionViewDidEnter

stackdisplay picture stackdisplay · Sep 25, 2017 · Viewed 42.2k times · Source

When we would not want to reinitiate a task that is already cache, there is no doubt that we will be using ionDidLoad.

Now, let's make assumption that we need to do a task each and every time when we are entering a view, how do we choose between using ionViewWillEnter vs ionViewDidEnter.

I did not find any clear guideline on this.

For example:
1) Getting navParams
2) Calling REST api
3) Declaring variable
4) Initiate something after DOM element loaded completely (eg: google map init)

Additional note:
I am note looking for an answer that is clearly written in the ionic documentation. What am I intend to know is what is the pros and cons if put in ionViewWillEnter vs ionViewDidEnter

eg: Initiating in ionViewDidEnter will cause some delay (for example, i am not sure about this) - even the insignificant one

Answer

Duannx picture Duannx · Sep 26, 2017

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.