How to use lifecycle methods in React? Example Tutorial

Components in React are the building blocks of an application. Every component in React has a lifecycle. In simple terms, every component goes through several different phases or events during its lifetime. These phases are -
  • Mounting
  • Updating
  • Unmounting
React provides several in-built methods for each of these phases. These methods are invoked at a certain time during the lifecycle of a component. Such methods are called lifecycle methods. This article will discuss some of the commonly used lifecycle methods in React.



1. Mounting State

Now, let's see what happens in the mounting state.

1.1 Constructor

The constructor is the first method that is called when a component is mounted. Similar to JavaScript, React’s constructor is also used for initializing.

In React, use the constructor to initialize the state and bind the methods. Any other code should be avoided in the constructor.

This is what a constructor in React looks like, very similar to what it looks like on Java or JavaScript:

class DemoComp extends React.Component {

constructor(props) {

super(props);

this.state = { count: 0 };

this.clickHandler = this.clickHandler.bind(this);

}

}


In the above code,  super(props) is called to access props, and this.state defines the state, and this.clickHandler is binding “clickHandler”



2. render state


The render method is mandatory in a class component. This method is called during the mounting as well as updating phase.

The render method is responsible for rendering the component in the user interface, thus making it the most important lifecycle method

Following is an example of the render method.

class DemoComp extends React.Component {
  render() {
    return <h2 > Hello World! < /h2>;
  }
}


The render method should return one of the following.
  • JSX (React elements)
  • Arrays and fragments
  • Strings and numbers
  • Portals
  • Boolean and null

The above example is returning a JSX code.  One important point to remember while using render methods is that it should be pure, meaning there should be no side effects. 

Though, you should never mutate the state in the render method.

How to use lifecycle methods in React? Example Tutorial




2.1 componentDidMount

The render method mounts the component, and the next method that is called immediately after mounting is called componentDidMount.  The componentDidMount method is one of the most widely used lifecycle methods because it is called right after the component is mounted.

It is regarded as the best place to call APIs. Moreover, unlike render methods, the state can be updated in the componentDidMount method.

So when the render method renders a UI, the componentDidMount is executed before the UI is displayed on the screen. If the state is updated in the componentDidMount method, the UI will re-render before displaying it on the screen.

So it is recommended to use the setState method in the componentDidMount method but with caution because carelessly using the setState method will lead to unnecessary re-renderings.




3. Updating state

Now, let's see what happens in this state for React components

3.1 shouldComponentUpdate

The shouldComponentUpdate method is a rarely used lifecycle method that is invoked just before re-rendering happens. As the name suggests, it is used to determine whether to re-render components or not.

The shouldComponentUpdate method is used for performance optimization as it has access to nextProps and nextState. It returns a boolean value, and by default, it is true. If the returning value is false, then the component will not re-render.



3.2 componentDidUpdate

The first method invoked in the updating phase in componentDidUpdate. This method is invoked as soon as any kind of update is made. The componentDidUpdate method is perfect for operating with DOM when the prop or state is changed. 

Remember, this method does not execute on initial rendering. It executes on updates only.  Moreover, the componentDidUpdate() method has access to previous props and states.
class DemoComp extends React.Component {

  componentDidUpdate(prevProps, prevState) {}

}

We can use the setState method in it but with a boolean condition to avoid unwanted situations.




3. Unmounting state

Now, let's see what happens to React Components in this unmounting state, which methods are called etc. 

3.1  componentWillUnmount

The componentWillUnmount() method is invoked just before the component is about to unmount and be destroyed. This method is basically used for cleanups.


The state should not be updated in the componentWillUnmount() method because it does not re-render. It should perform cleaning actions such as clearing caches, clearing timers, or canceling API calls.


That's all about the lifecycle methods in React.js. So these were the commonly used lifecycle methods in React. Every method is executed at a certain time. So if used properly, these methods can be very useful. 

Remember, these lifecycle methods are only available in class-based components. In functional components, we can use the useEffect hook in different ways to achieve functionalities similar to some of the commonly used lifecycle methods.

Other React.js  Articles and Tutorials you may like

Thanks for reading this article so far. If you like this React tutorial about lifecycle methods, please share it with your friends and colleagues. IF you have any questions or feedback, then please ask in comments. 

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.