Purpose of ionViewDidLeave()

Hello!

So I made an app where there are a couple of pages with a timer. The weird thing is, even when I go to a new page, the timer from the old page continues counting down. Is this one example where one should use ionViewDidLeave() ? What is the general purpose of it?

Yes, that’s an example. The page remains active until some time after it’s removed from the nav stack. So if you want variables to only exist when the page is visible, a standard way to achieve that is to use life cycle hooks to initialize when you enter, and to clean up when you leave.

1 Like

It really depends on how you’re setting up your navigation stack and what plugins that you’re using.

One example of how I use ionViewDidLeave() is to unload audio that I load on ionViewDidEnter().

I’m using the ionic-native-audio plugin to play short audio clips and once a user navigates to the next page I unload the files to reduce memory use.

1 Like

Could I expect the same behavior with setRoot as well (instead of push) ? Will the previous page still remain active for a while?

setRoot removes all other pages from the nav stack. So that’s different from being on page1 and you push page2. page1 will still exist forever. Once you pop page1, it gets queued for destruction. setRoot queues all existing pages for destruction except the new root page. How long does a page remain in the queue? Ionic only guarantees that it will eventually happen. So maybe it is instant, but I program as though pages wait forever. So I clean up literally everything in ionViewWillLeave(), and don’t count on the NavController to do it for me. Maybe too paranoid, but it works.

1 Like

Yes, that’s a practice I’m going to adopt as well. The same can be done in either ionViewWillLeave() or ionViewDidLeave() right?

Yes. I haven’t run into a situation where I needed to care which of the two I used. I’m sure the difference matters in some applications, but for what I’ve needed, they feel the same.

1 Like