React Lifecycle Hooks

In this article, we are going look through a few of the most common lifecycle hooks we can use with React components, and we will discuss why they are useful to your React components.

Introduction to Lifecycle Hooks

React is a JavaScript library for building user interfaces. The user interface in a front-end application is implemented by using components. A user will interact with these components by clicking, hovering, pressing a key, submitting a button and so on. Thus, the core of any React application are the components. They have a significance inside the browser DOM. This significance is represented as if each component has its own life when it is rendered by the browser.

Lifecycle hooks are pre-defined functions in React API that leverage over the life of each component in the browser. These different methods can be invoked at different phases of the lifecycle of a component. Suppose if we are creating the video streaming app, then obviously our app will use the network to buffer the videos and it spends the battery power. If the user switches to another application after playing the video, then as a developer you should make sure that you are using the resources like network and battery in the most efficient manner. Whenever the user switches to another application, the app can stop/pause the buffering of the video, which will stop using the network and battery.

To make sure as a developer to produce an application that has the quality of code as well focuses on better user interfaces, lifecycle methods are a huge part of ReactJS ecosystem.

Four Phases of React Application

Each component in ReactJS has four following phases:

  • Initialization
  • Mounting
  • Update
  • Unmounting

Take a look at the below image to get a visual representation of how four phases in ReactJS dwell. (ss1)

Initialization Phase

In the initialization phase, the React component prepares for the upcoming tough journey, by setting up the initial states and default props.

class VideoPlayer extends React.Component {
    state = {
        volume: 70,
        status: 'pause'
    };

  VideoPlayer.defaultProps = {
    theme: 'dark'
};
}

In above you can notice that the component is setting up the initial state with a volume of 70 and status of pause. The defaultProps is defined as a property of Component to define all the default value of props, which can be overridden with new prop values.

Mounting Phase

Once the bare minimum needs of a React component that includes state and props are fulfilled, the component is ready to be mounted in browser DOM. The mounting phase provides the following methods to mount React components.

  • componentWillMount: This method is executed before the React Component is mounted on the DOM. During this step, before this method gets invoked, you can do all those things that are required to do before a component gets a mount. This method is executed only once in the lifecycle of a React component. This happens before the first render.
  • render: This is another method that is mandatory to be mounted in the browser DOM. This method will always give the same output depending on the input is provided. This makes the render method a pure function.
  • componentDidMount: This is another hook method which is executed immediately after the component did mount on the dom. This method is executed once in a lifecycle of a component and after the first render. You may call setState() immediately in componentDidMount(). It triggers an extra render of components which happens before the browser updates the screen. Another thing note that, whenever you are making AJAX requests a third party API or your own internal backend system, each request has to be made inside componentDidMount

 

componentDidMount() {
    fetch("https://api.example.com/items")
      .then(res => res.json())
      .then(
        (result) => {
          this.setState({
            isLoaded: true,
            items: result.items
          });
        },
        (error) => {
          this.setState({
            isLoaded: true,
            error
          });
        }
      )
  }

Updating Phase

This phase starts when a React component has is registered in DOM tree on the browser and is ready to receive new updates. There are two ways to update a component. The first one is by sending new props and the second way is to update the existing state. The methods that you can use to update a React component are:

  • shouldComponentUpdate tells the React that when the component receives new props or state is being updated, should React re-render or it can skip rendering? The method returns true or false, and accordingly, the component would be re-rendered or skipped. By default, this method will return true.
shouldComponentUpdate(nextProps, nextState) {
  let shouldUpdate = this.props.status !== nextProps.status;
  return shouldUpdate;
}
  • componentWillUpdate: This method gets executed only after the shouldComponentUpdate returns a boolean true. You cannot call this lifecycle hook after the initial rendering method. Also, note that it is better to avoid invoking setState() inside this hook.
  • componentDidUpdate: Whenever a component gets an update, this method gets invoked internally. You can further use it to trigger the third party libraries used to make sure these libraries also update and reload themselves.
  • componentWillRecieveProps: Before a component receive props, this method gets invoked. To update the state in case of receiving new props in a component, you will need to pass the arguments, props, and nextProps and compare them in order to perform state transitions using this.setState(). Note that if a parent component causes your component to re-render, this method will be called even if props have not changed.
componentWillReceiveProps(nextProps) {
  if (this.props.status !== nextProps.status) {
    this.setState({
      status: nextProps.status
    });
  }
}

Unmounting Phase

During this phase, when a component is not needed or when a component is done rendering the values on the UI, it gets unmounted from the browser DOM. The following is the only method which is called during this phase.

  • componentWillUnmount: It gets executed immediately before a component is unmounted and destroyed. To perform any necessary cleanup such as invalidating timers, canceling AJAX requests that were created in componentDidMount() are done inside this lifecycle hook.

You should avoid invoking this.setState() in componentWillUnmount() because the component is re-rendered after it gets destroyed.

Leave A Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.