Ionic By Component: Page Lifecycle

07 December 2016 / By Sani

In Ionic, each view in your Ionic mobile application is actually an Angular 2 @Component. However, we normally refer to each view as a Page in Ionic. Each Page in ionic is arguably stateless after it is fully instantiated, however Ionic does provide us with some nice events which we can capture and perform specific tasks on a Page during its lifecycle. These events are part of the Page lifecycle of any Ionic Page you create. To explain what a life cycle is and why the functions exposed in a lifecycle are important, let us consider the fictional example of my very fictional friend Perry.

Perry works for a company called Drifty and is an exceptionally organized individual. Perry depends on his alarm for everything to get him through his day and remind him of all his activities & meetings. So in the morning, his alarm would notify him to wake up at 7AM. At 10AM his alarm would go off again to remind him of his morning meeting at his office. At 1PM his alarm would go off again to let him know its lunch time. At 4PM it would go off to remind him to catch the bus home. At 7PM it would go off yet again to tell him to order dinner and watch his favorite TV show and finally, at 11pm it would go off to signal time to go to bed. Perry relies on this every day to remind him of how to manage his day and when to do cool things during his day. Now if you were patient enough to read my little story about Perry, then I'm happy to inform you that it's very similar to how lifecycle events in Ionic work. Think of Perry's day as an Ionic Page and think of each alarm that goes off as a lifecycle event of each page.

These Lifecycle events in Ionic basically inform you at specific intervals of a Page's about what state a page is in from its creation until its destruction so you can perform some awesome tasks. So what are these lifecycle events that each Ionic Page possesses?

 

Ionic Page Lifecycle Events

ionic-page-lifecycle

Ionic Page Lifecycle



constructor()

This is actually a standard ES6 class feature and not directly provided by Ionic. This is the very first lifecycle event that is fired when the page is being instantiated and you cannot guarantee that everything within your class is ready and available for use. The constructor should be kept as thin as possible & you should only be initializing the variables of your class and maybe firing off delegation events. You should avoid making calls to your REST API here to setup data here, as this could delay the creation of your class and slow down your application or cause some very weird unexpected behavior.The constructor only ever fires once when the page is being created and is never called ever again.

 constructor() {
    this.movie = 'Avatar';
    this.director = 'James Cameron';
    this.hero = 'Jake Sully';
    this.girl = 'Neytiri'; 
  }


ionViewCanEnter()

This event is more of a navigation guard. You would normally implement this function to ensure that a view can be entered only if it fulfills some preconditions. The ionViewCanEnter() function expects a boolean returned so you have to return either true or false at some point for it to work. Consider a case where you want to lock some of your application to premium users only, or it could be a case where you require users to be logged in or maybe you want to simply prevent non-admin users from entering a page. You can implement the ionViewCanEnter() function within the class associated with that particular page to check if the user has the right permissions or satisfies the conditions needed to enter a page. This lifecycle event is the very first to be called in the navigation sequence and also fires every single time the page is being navigated into and will check to see whether it returns true or false and then carry on the navigation or fail the navigation and throw an error on the previous page we were trying to navigate from which you can handle in your code and react accordingly.

ionViewCanEnter(): boolean {
    if(userIsLoggedIn){
      return true;
    } else {
      return false;
    }
  }


ionViewDidLoad()

The ionViewDidLoad() event fires to signal that all your variables and dependencies are good to go and ready to be used. This also means that the page has been added to memory and it can be cached in future. This is event only fires once and only once like the constructor() function but the difference is that at this point, you can be sure that all your variables & dependencies injected are available for use. This is the function where you would want to make all your initial HTTP calls to get your data and do the main heavy lifting of your application. You must be aware that the code you run here is only called once so only do one time heavy lifting here.
ionViewDidLoad(){
    this.mydata = myDataService.getData();
    this.runSomeVeryComplexFunction();  
  }


ionViewWillEnter()

Despite your page being fully loaded from the code perspective, there is still a lot of magic still being done behind the scene to make your page fully active and made visible to the user. Ionic still has some internal logic to handle things like transitions animation to handle in order to bring your page into view and make it interactive. The ionViewWillEnter() lifecycle function tells you that all that process to make your page in full view and transitioned in is about to begin and your page has been queued to be pushed into view. At the stage that this function fires, it is likely that your page is actually not in view even though you have the ability to manipulate the page's elements. This is a great place to hide and show things on your page before it is made visible to the user.

Another great use case for this function is to update your view. Let's say you have something like a timer you want to keep track of on a particular page, and let's assume that your app is constantly updating this timer on the page. When you navigate away from this page, you will most likely keep this timer but ideally, you don't want to be updating the view. However, as soon as you navigate back into the view, you want to update the latest value of your timer but you would want this latest value to be updated just before the page is in view so you don't see a flicker. This is a perfect sample use case for the ionViewWillEnter() lifecycle function. I do not recommend that you load critical data in the function as it could mean that your app might see slow since you could ideally have done that heavy lifting in the ionViewDidLoad() function.

ionViewWillEnter(){
    this.latestHilaryClintonVoteCount = this.myElectionService.getFromEmailServe();
    this.latestDonaldTrumpVoteCount = this.myElectionService.hasWorldEnded();
    this.numberOfStatesLeft = this.myElectionService.getStatesLeft();
  }


ionViewDidEnter()

This function is what basically screams that all is well and good and our page has fully loaded and has fully entered into view. It is the final function that fires when navigating into a page as part of that page's lifecycle. The one guarantee that this function can offer you is that your page is definitely the one being viewed and that the transition animation alongside any internal setup is complete. So what is this particular function needed for and when is it a good time to use it? Well, first this is the place you want to write any logic or trigger any feature of your app that you definitely want the user to see very early on, or maybe the very first thing that you want them to interact with. Consider a case where you want to either show a user some initial feedback or let's say you want to do some onboarding for your app for new users. This is a perfect place to showcase such feedback information. This view also fires multiple times both when you navigate to the page for the very first time, and anytime you navigate backward into it. It can also be used to do all the things that can be done in the ionViewWillEnter() method as long as it doesn't require your page to be nonvisible.

ionViewDidEnter(){
    this.showInitialFeedback();
    this.beginOnboardingProcess();
  }


ionViewCanLeave()

The ionViewCanLeave() function is the reverse of the ionViewCanEnter() function and is also sort of a nav guard function that returns true or false. This function exists to be used to conditionally stop the user from leaving the page. It is a boolean function so whatever code you execute within it will have to return true or false before another step of the navigation is fired. A good use case for this function could be in the filling of forms. Imagine where a user is filling a form and maybe tries to navigate away from the page before finishing a form. You can use this to function to stop the user from leaving and maybe politely notify the user to finish the form or risk losing their data. This function can also be used for authentication checking. You could stop a user from leaving a page if they do not have the correct permissions to access the page they are trying to navigate to. This function also fires every single time you try to navigate forwards away from the page so you can take advantage of that to implement some intelligent guards for your page.

 ionViewCanLeave(){
    if(this.userHasNotFinishedForm && this.userDoesntHavePermissionsForNextPage){
      return false;
    } else {
      return true;
    }
  }


ionViewWillLeave()

This function signals the intent of your page to actually start being taken out from being the currently active page. At the point this event fires, it is still the active page but it has been queued up to be removed and you can no longer prevent the page from being transitioned away from at this point. This function can be a good place to start preparing for data to be used in the next view. For example, you can use this to make an asynchronous call to some API that will be needed in the very next view. This function also fires anytime the view is being navigated away from so this means any code you put in here will be executed every single time your page is being left.

 ionViewWillLeave(){
    this.myService.prepareSomeDataForNextView();
  }


ionViewDidLeave()

This is the event that signals to you that your page is no longer the page in focus. The ionViewDidLeave() function only fires after the ionViewDidEnter() function of the next page has fired. Now you might be wondering what will be a good use case for the ionViewDidLeave() function. This function is a great place to save data or states from the page you are leaving as well as triggering some background operations that don't require the view being visible. It is worth remembering that this function also fires every single time you are leaving this view and navigating forwards. So for example, if you are in Page1 and you navigate forwards to Page2, this event will fire and when you come back to Page1 and navigate to Page2 yet again, the same function will fire.

 ionViewDidLeave(){
    this.saveMyState();
    this.fireOffSomeOtherNonBlockingCode();
    this.ensureWeAreNotUpdatingTheView();
  }


ionViewWillUnload()

The ionViewWillUnload() function is the final function to fires in the lifecycle of a typical page. This function behaves slightly different from the rest of the page lifecycle functions. Firstly it is pretty much like the ionViewDidload() function so this means it only ever fires once. Also, it only fires when we are navigating backward. So for example, if we are on Page1 & we navigate to Page2, this event will not fire for Page1 because page one is actually still loaded and cached in memory even though it is no longer in view. But as soon as we hit our back button on Page2 to go back to Page 1, this event will fire for Page2 because we will be navigating backward so Page2 is no longer in memory and it will be unloaded and this function will be called.

 

The ionViewWillUnload() function is perfect for freeing up resources no longer needed and all sorts of cleanup to avoid possible memory leaks. You can also use it as a place to save states and cache data you might be needing later on. This function only runs once and is your last stop before the page is destroyed and unbound from the view with all its elements removed.

 ionViewWillUnload(){
    this.myObservableThatUsesResources.unsubscribe();
    this.someKindOfStream().close();
    this.someKindOfEventListener.unlisten();
    this.saveMyLocalData();
  }


Round Up

As you have learned from this post, the page lifecycle events available to every Ionic page can be used to do some very powerful things at different phases of a Page's lifecycle. The web is stateless by nature but these lifecycle events go a long way to providing a way to hook into different phases of the life of a page and mimic the statefulness that is normally available in the native development environment on IOS & Android. It is very important to use these interfaces correctly and only when needed as misuse of them could introduce some improper behavior into your app and affect the user experience of your app. Stay tuned for more posts on the Ionic By Component series and be sure to share this post if you enjoyed it. I am also happy to answer any of your questions in the comments section.



  • Manoj Kumar Mobile App Dept

    which will work if i lock the sceen

  • Amit Shakya

    Is it work in IONIC 3??? I tried it’s not working…