React – Component Lifecycle

React is all about components. But only rendering and using props is not enough to build real-world applications. We need to do asynchronous operations like fetching data and setting timeouts. These are also called side effects.

Understanding the component lifecycle and ways to deal with it is extremely important. It helps us to fully control a component and handle state and prop updates at appropriate places.

The lifecycle of a Component

A component goes through different stages, from its creation to destruction. When React has to render a component to the DOM for the first time, it is called the mounting phase.

A component will then live its life serving the user by listening to events, updating props, changing the state, etc. Various updates and changes occur due to the user’s interaction. React handles those by re-rendering the component multiple times, whenever necessary. This phase is called the updating phase.

The phase When a component is about to be removed from the DOM is called the unmounting phase.


Component Lifecycle Methods

React provides methods that allow us to hook into the lifecycle of a component. Using these methods, you can run some specific code in a specific stage.

It is worth looking at the chart below to overview the lifecycle methods and when they are executed.

 

React has methods to run code for each of the three phases – mounting, updating, and unmounting. The chart also shows the order in which these methods are executed. For each lifecycle, the mounting and unmounting phase runs only once, but the updating phase may run any number of times.

Note that lifecycle methods are only supported in class components and not in functional components.

Any code that we put inside these hooks (lifecycle methods) will help us to perform side effects and other state updates.


Mounting Lifecycle Methods

Constructor

First, the constructor() of the class component is called before any rendering or mounting is performed. We can initialize the state and optionally bind this to class methods inside the constructor.

Inside the constructor, we can directly initialize the state through the this.state property. This contrasts with other methods where we have to use this.setState() instead to update the state.

Do not perform any side effects, such as fetching data from a server inside a constructor. This will likely cause unexpected behavior and should be avoided.

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            num: 1
        }
    }
    render() {
        }
}

Render

The render method is called once the constructor has been executed. It should return a React element. In the mounting phase, after the rendering completes, the component is inserted into the DOM.

class App extends React.Component {
    render() {
        return ( <div>
            <h1> Lifecycle in React </h1> 
            <p> rendering... </p> 
                 </div>
        )
    }
}

ComponentDidMount

React calls this method right after the component is mounted to the DOM. You can perform any side-effects in this method. Remember that this method is called only once in the mounting phase when the component is created.

componentDidMount() {
    fetch('https://jsonplaceholder.typicode.com/todos/1')
        .then(response => response.json())
        .then(json => {
            console.log(json)
            // perform state updates here...
        })
}

It is always best to execute the code that you want to run only once at the beginning when a component is mounted. Common use cases include fetching initial data from a server, such as loading a list of products.


Updating Lifecycle Methods

ShouldComponentUpdate

A prop or state update may happen when the event listener methods are executed on user interaction. Whenever any prop or state of a component changes, the render method is executed. Any child components are also re-rendered to ensure the update is reflected in them.

However, there may be cases where you may want to control auto-rendering behavior by React. This is possible by returning a Boolean value from the shouldComponentUpdate() lifecycle method. Rendering is done by React only if “true” is returned.

Most of the time, a component spends its life in the Update lifecycle, compared to mounting and unmounting lifecycles. It keeps on waiting for any changes to the component and updates the DOM to show the changes.

shouldComponentUpdate() takes nextProps and nextState as arguments that will be rendered.

class App extends React.Component {
    shouldComponentUpdate(nextProps, nextState) {
        if (nextProps.someData !== this.props.someData) {
            return false
        }
        return true
    }…
}

Render

We have already discussed the render method before. It is also executed in the update lifecycle to show the changes to the DOM. But there is one important tip to remember: “Never update the state or perform any side effects inside the render method.”

If any state is updated in the render method, it will trigger the update lifecycle again and re-run the render method. This will keep calling render again and again until the program crashes.

ComponentDidUpdate

This lifecycle method runs after render() when the DOM has been updated. We can perform side-effects or any updates inside the componentDidUpdate() method.

It is necessary to put some condition before updating any state. This is to avoid any possible infinite loops. ComponentDidUpdate() takes two arguments: prevProps and prevState, which help us to compare the previous state with the current state.

componentDidUpdate(prevProps, prevState) {
    if (prevProps.someData !== this.props.someData) {
        // perform some update
    }
}

One practical example is using the componentDidUpdate() to send a save() request to the database on every change to an input.


Unmounting Lifecycle Methods

This is the last phase where the component is removed from the DOM by React.

ComponentWillUnmount

This hook runs just before the component is unmounted. We can use this method to free up any memory or event listeners and timers that were set using other methods.

Note that you cannot perform any state updates because the render method will not be called in the unmounting stage.

componentWillUnmount() {
    clearTimeout(timer)
    // or other code to do cleanups
}

After this method, the component is unmounted from the DOM and won’t exist anymore unless some other component recreates it.


Other lifecycle methods

We have discussed the most important lifecycle methods. But some more lifecycle methods are rarely used and not required in most cases.

You can always look them up in the official react docs if you need more control over your components.

  • static getDerivedStateFromProps()
  • getSnapshotBeforeUpdate()

For error handling:

  • getDerivedStateFromError()
  • componentDidCatch()

And three other legacy methods that should be avoided as it has the potential to cause bugs and errors:

  • UNSAFE_componentWillMount()
  • UNSAFE_componentWillReceiveProps()
  • UNSAFE_componentWillUpdate()

Conclusion

React lifecycle methods give you the full control to take advantage of the component’s benefits. Class components only support them. Any practical react application requires the use of these methods. Using only the render method is never enough unless it’s a static component, and hence the need for lifecycle functions.

Back to: React Tutorial > Learn React

Leave a Reply

Your email address will not be published. Required fields are marked *