Learn about lifecycle methods in React.
Now that you're done with your first project, you are on your way to becoming advanced with React. So let's talk about some more advanced topics. The first will be lifecycle methods. This is an incredibly important topic, so pay close attention and make sure you understand everything.
Lifecycle methods are special methods built-in to React, used to operate on components throughout their duration in the DOM. For example, when the component mounts, renders, updates, or unmounts. You already know the most important lifecycle method, the
rendermethod. Soon you will know a few more, with a good understanding of when to use them and what tasks should be done within them.
One important thing to notice is that lifecycle methods can only be used in
class components. In functional components we have other options. But more on that in the next lesson. Let's begin.
- Understanding the lifecycle of a component
- Knowing the most important lifecycle methods
- Understanding which tasks should be done in the different lifecycles
As stated in the introduction, a component's lifecycle is the sequence of stages an instance of a component goes through in the DOM (or virtual DOM in React's case). Let me give you a quick example:
- 1.Creation of the component (componentDidMount)
- 2.Render of the component (render)
- 3.(Optional) Update of the component (componentDidUpdate)
- 4.Death of the component (componentWillUnmount)
A component can be in different states of its "life", and in React we can use those states to handle certain tasks.
We are already familiar with the render method in React, each class component needs to contain a render method, and it is fairly simple to understand. The render method contains all the logic your component should display on the screen. It might also contain a null value, if you don't want to show anything. (Conditional rendering! Look it up!)
As the name already suggests, this method is run when the component is mounted, meaning when it is inserted in the DOM tree.
Common tasks that are done in this method are:
- Set Timers using setTimeout or setInterval.
- Add event listeners.
This method is not called for the initial render, but any other time when the component updates. This method is a great place to work and operate on the DOM when the component has updated. For example you could do network requests. Just make sure to compare it to the current props.
This is the last lifecycle method, which will be called when the component is removed from the DOM tree. Usually you would do cleanup tasks in this method. This often includes cleaning up what you added in the componentDidMount method.
A few examples are:
- Remove event listeners
- Cancelling network requests
- Other cleanup routines