React Lifecycle methods explained
In React components have many lifecycle methods that we can use in different phases of the component existence. The lifecycle of a component is consisted of three main phases: Mounting, Updating and Unmounting. Lets look at each one of these phases and the methods associated with them.
This phase is usually referred to as the birth of the component. It’s at this phase that the component is created and inserted into the DOM. Some of the most used methods in this phase are: constructor, render and componentDidMount
The constructor method allows us to initialize the state and also to bind event handling methods. Constructor gives us access to props by passing in props as an argument to constructor and calling super(props) inside the constructor.
This method is the one responsible for rendering the component into the UI. Render does not modify the state, and it’s required in all class components.
componentDidMount is invoked after the component gets mounted on the DOM. As opposed to render, componentDidMount allows for modifying the state. ComponentDidMount is usually used for doing API calls to fetch data from a remote endpoint. It’s also used to set subscriptions.
This phase is triggered whenever a component gets updated by a change in the state or the props. The most used lifecycle method at this phase is componentDidUpdate.
This method is called when the component got updated. componentDidUpdate is best used for manipulating DOM elements after the component gets rendered.
This phase is also called the cleanup phase, and the only method that we have in this phase is componentWillUnMount
This method is called before the component is unmounted or removed from the DOM. It’s usually used to clean-up subscriptions that are created in componentDidMount.
I also want to mention that these methods are only accessible in class components. In functional components, however, you can use hooks to achieve the same result.
As you can see, in React, components have many lifecycle methods that we can use to override and run code at a particular time in the process. These lifecycle methods belong to three phases: Mounting, Updating and Unmounting. Here is a diagram from the React docs to understand this more clearly.
Thanks for reading :)