Lang
Blog

What are Component Lifecycle Methods in React JS??

Like us all, React components also take birth, grow, and die!

ByPayal Mittal
December 7th . 5 min read
What are Component Lifecycle Methods in React JS?

Every React class component goes through a series of “lifecycle methods”. Basically, everything in React is consist of either components or a part of the components.

These components are subjected to follow a certain lifecycle, almost like that of any living creature on earth. They take birth, grow, and then die at last. The phase when they are born is called mounting, when they grow is called updating, and the last phase of death is known as unmounting.

This whole process is called ‘Component Lifecycle’. For each of these phases, React.js renders certain built-in methods referred to as lifecycle methods which control the behavior of components within an application.

In this blog, we’ll go through this lifecycle and get to know about these lifecycle methods-

What are Component Lifecycle Methods?

The component lifecycle methods are divided among three different phases, as-

  • Mounting
  • Updating
  • Unmounting

The entire component lifecycle can be understood by this simple visual illustration -

component-lifecycle-methods-in-react-js_1.jpg

Now, we’ll discuss each of the phases and their methods in detail. Let’s go then -

✔ Mounting lifecycle methods

After completing the component initialization, component mounting begins in which the component is created and inserted into the DOM.

Here, we’ll discuss the most commonly used lifecycle methods-

1. constructor()

The constructor() is called first before the mounting begins and is basically used to serve these two purposes-

  • To initialize the local state of a component
  • To bind event handling methods to an instance

Instead of using setState(), you can directly assign the initial state to this.state() in constructor method. Here is how we can define our state-

constructor(props) {
  super(props);
this.state = { count: 0 };
  this.handleClick = this.handleClick.bind(this);
  console.log("Constructor!");
}

2. render()

Next in line is the render() method! It mounts the component onto the DOM and renders them to the UI. This method gets invoked to examine this.state and this.props attributes whenever there is any variation in the component’s state or props.

render is the most commonly used method of all in React. If you want to render elements in the DOM, then render() is the method to look forward to because you can write them here.

Whenever called, it can return many types, i.e. strings, numbers, arrays, fragments, Booleans or null value, portal, or React elements. Some examples are given here -

class MyComponent extends React.Component {
   render() {
//return string
    return "Hello!!"
//return null value in case you don't want to render anything
    return null
//return fragments   
    return <React.Fragment>
            <div>Hello</div>
            <div>Friends</div>
      </React.Fragment>
//return arrays        
      return [
          <div key="1">Hello</div>, 
          <div key="2">World</div>
      ];
 }
}

Note: If the componentShouldMount method returns boolean false, then the render method will not be evoked.

3. componentDidMount()

This method is called immediately after the component is inserted into the DOM via the render method. It is called only once in a lifecycle.

  • If you’re looking to set up any subscriptions, then this is as good a place as any to do so. But, you’ll have to unsubscribe in componetWillUnmount().
  • Also, it is a good place to instantiate a network request if you need to load data from a remote endpoint.
  • You can even call setState() here. Although it will further trigger a rendering again, you won’t see the intermediate state at least. However, you must be cautious while using this because it causes performance issues. In fact, you should assign the initial state in the constructor() method, as advisable. But this approach comes in handy when you need to measure a DOM node before rendering something that depends upon its size.

✔ Updating lifecycle methods

Unlike the ‘Mounting’ phase that occurs only once while mounting the component, the ‘Updating’ phase can occur multiple times.

Whenever there is any change in the props/state of the component that needs to be updated, a timer calls for render and componentDidupdate to acknowledge, update, and render the change, the Updating phase comes into play.

1. static getDerivedStateFromProps()

This is the first method that gets called in the updating lifecycle phase. It can be called multiple times because it gets invoked whenever the render method initiates. So, it is obvious that it is called during both mounting and updating phases.

This method is not very common and rarely used in specific cases, for instance when the component’s state varies with changes in props over time. As the name implies, it derives state from props.

2. shouldComponentUpdate()

This method is called when the component is about to re-render. It determines whether the current changes in the states/props are affecting the component’s output. It is only used as a means of performance optimization and let us know ‘should the component update or not’, which is expressed by Boolean true or false values. By default, it returns true.

If shouldComponentUpdate() returns false value, it means you’re telling React to skip this update and thus, render and componentDidUpdate methods will not be called.

component-lifecycle-methods-in-react-js_2.jpg

However, you can also prevent unnecessary rendering by using built-in React.PureComponent which lets you compare the new and old state/props and makes it unlikely for you to skip any necessary update.

3. render()

Next comes render. Whether or not it will be called depends upon the value returned by shouldComponentUpdate. It will trigger only in the case when true is returned.

4. getSnapshotBeforeUpdate()

After render is called, getSnapshotBeforeUpdate comes next. It is not commonly used but comes very handy in certain specific cases, such as when you need access to some information in the DOM and change it, right after it has been updated.

This method allows the component to capture some information (scroll height) from the DOM so that it can be adjusted later (after updating). Though, you need to understand that the scroll height captured here indicates the height before it was updated to DOM.

We can pass prevState and prevProps as arguments, as given here -

getSnapshotBeforeUpdate(prevProps, prevState) {
return null;
}

5. componentDidUpdate()

This method gets invoked immediately after the component is updated and re-rendered. It receives the prevState and prevProps as parameters and can also access the newly changed state or props.

However, it is strongly advised to never directly set the state within this function, otherwise, it will further trigger render and componentDidUpdate.

Through this method, we get to calculate the scrollHeight difference between what it was before after getting updated.

This is only one use-case, there are several others like -

  • 👉 To fetch data from the server

  • 👉 To access the DOM nodes of the React component

To get details about its use cases, check out the official documentation.

✔ Unmounting lifecycle methods

This is the last phase in which a react component goes through where it gets unmounted from DOM and destroyed. There is only one lifecycle method in this phase.

1. componentWillUnmount()

componentWillUnmount method is called first in the unmounting phase, just before the component is destroyed. This is the place where you can perform any cleaning method, essentially canceling network requests, invalidating timers, or cleaning up unwanted subscriptions that were created in the componentDidMount method.

Summary:

There are some other methods that are invoked in case an error is thrown by a descendant component, these methods are called error handling lifecycle methods. You’ll find them here.

That was all coders!! I hope that you get a better understanding of the React component's lifecycle methods through this blog. Get back to you soon with another insightful blog.

**Till then, happy reading!!**🙃

Share:
0
+0