This chapter covers
- Understanding a lifecycle hook
- Executing code when a component is mounted
- Executing code when a component is unmounted
- Publishing version 4 of the framework
It’s not uncommon for a component to execute some code when it’s mounted into or unmounted from the Document Object Model (DOM). The classic example is fetching data from a server right after the component is mounted. In that case, the component is already part of the DOM, so it can display a loading indicator while the data is being fetched. When the data is ready, the component updates its view by removing the loading indicator and rendering the newly fetched data.
Your existing framework runs code only when a user-originated event happens, such as clicking a button. (Technically, it could also run code as part of a setTimeout()
or setInterval()
callback, but let’s omit this possibility for the sake of simplicity in the explanation.) It can’t fetch data when a component first shows up, which is a limitation because developers can’t make code run before the user interacts with the page.
A lifecycle hook is a user-defined function that is executed when a component goes through a lifecycle event. Lifecycle events include the creation, mounting, updating, and unmounting of a component. In this chapter, you’ll explore how lifecycle hooks fix the aforementioned limitation and how to implement them in your framework.