Skip to main content

Development

React Js – Component Life Cycle Methods

Blog Introduction:

React Component Lifecycle Methods are the functions that are executed on the course from a component import to rendering in the view.When a view is rendered through react i.e., a react component it goes through 4 phases. Initialization, Mounting, Updating and Unmounting in this specified hierarchical flow. Of which Updating may or may not occur based on the user scenario in which case the Initialization, Mounting and Unmounting will occur.

Once a Component is fully mounted i.e., rendered in the view and if the users closes the browser window without unmounting it then the component will not go through the Unmounting phase also.

Target Users

  • Front End Developers
  • Beginner React js developers to get a wider understanding of the React Component rendering mechanism
PreRequisites

  • Intermediate knowledge of HTML5/Css
  • Knowledge Browser DOM view render mechanism
  • Intermediate knowledge of Javascript/Jquery
The below Flow illustration shows the various lifecycle methods executed at the appropriate timeline during a component rendered.

ReactComponentLifeCycle

  1. Component Initialization
The initialization phase is where we define defaults and initial values for this.props and this.state by implementing getDefaultProps() and getInitialState() respectively.

The getDefaultProps() method is called once and cached before any instance of the component are created. This method returns an object which properties values will be set on this.props if that prop is not specified by the parent component.The getInitialState() method is also invoked once, right before the mounting phase. The return value of this method will be used as initial value of this.state and should be an object.

Code Example
//getDefaultProps
var Person = React.createClass({getDefaultProps: function() {
return ({ age: ‘unknown’ });
},
//…..
});
//getInitialState
var MessageBox = React.createClass({
getInitialState: function() {
return {nameWithQualifier: ‘Mr. ‘ + this.props.name};
},
//…
});
  1. Component Mounting
The Lifecycle methods that go through in the mounting phase are,

  • componentWillMount()
  • render()
  • componentDidMount()

componentWillMount()

The componentWillMount() method is the first called in this phase. It’s invoked once and immediately before the initial rendering occurs, hence before React inserts the component into the DOM. It’s very important to note that calling this.setState() within this method will not trigger a re-render.

Since this method is called before render() our Component will not have access to the Native UI (DOM, etc.). We also will not have access to the children refs, because they are not created yet. The componentWillMount() is a chance for us to handle configuration, update our state, and in general prepare for the first render.

Code Example
// Invoked once before first render
// Calling setState here does not cause a re-render
componentWillMount: function(){
alert(‘In Component Will Mount’);
},

render()

This is the method we go through when we first have the actual rendering of the component in the DOM. We create Elements (via jsx/js) and return them. We access the Component this.props and this.state and let these values derive how content should be generated. A real scenario would be the show/Hide of a component on first load.

render() is the method unlike others, goes through multiple component phases like on mounting, updating. A user triggered update shall go through the updating phase which will also be rendered in the DOM via the render() method.

Code Example
// Invoked once before first render
render() {
return(
<div>
<Carousel />
</div>
)
}

componentDidMount()

The last step in the Birth/Mount life cycle phase is our post-mount access via componentDidMount(). This method is called once all our children Elements and our Component instances are mounted onto the DOM. When this method is called we now have access to the Native UI (DOM, UIView, etc.), access to our children refs and the ability to potentially trigger a new render pass.

Code Example
componentDidMount() {
axios.get(‘/appData.json’).then((result)=> {
this.setState({
appData: result.data
});
})
}
  1. Component Updating
A typical example of a component updating phase is when an user trigger updations like state value change trough a function executed on user events like onClick, onChange etc. What follows is a set of component state/props change usually and the component render occurs updating the DOM accordingly.The Lifecycle methods that go through in the updating phase are,

  • componentWillReceiveProps()
  • shouldComponentUpdate()
  • componentWillUpdate()
  • render()
  • componentDidUpdate()

componentWillReceiveProps()

The first method available to us is componentWillReceiveProps(). This method is called when props are passed to the Component instance. This is the first hook that allows us to look into the upcoming Update. Here we could extract the new props and allows us to check and see if new props are coming in and we can make choices based on the data.The componentWillReceiveProps() can be skipped if the Update is triggered by just a state change.

Code Example:
componentWillReceiveProps( nextProps ){
this.setState({ hide: nextProps.hide });
}

shouldComponentUpdate()

The shouldComponentUpdate() method allows your Component to exit the Update life cycle if there is no reason to apply a new render. Whenever a component’s state changes, React re-renders the component and all its children. Often times, the component and its children barely change yet we need to render everything causing an inefficient code rendering.

This lifecycle method checks the current props and state, compares it to the next props and state and then returns true if they are different, or false if they are the same. Based on the Boolean value, we shall be able to avoid rendering when it isn’t needed.

Code Example:
shouldComponentUpdate(nextProps, nextState) {
if (this.props.color !== nextProps.color) {
return true;
}
}

componentWillUpdate()

Once we have determined that we do need to re-render in our Update phase, the componentWillUpdate() will be called. The method is passed in two arguments: nextProps and nextState. The method componentWillUpdate() is similar to componentWillMount(), and many of the same considerations and tasks are the same. The difference being that componentWillUpdate() is called every time a re-render is required, such as when this.setState() is called. Unlike componentWillMount() we get access to the next props and state.

Just like componentWillMount(), this method is called before render(). Because we have not rendered yet, our Component’s access to the Native UI (DOM, etc.) will reflect the old rendered UI.

Code Example:
// dispatching an action based on state change
componentWillUpdate(nextProps, nextState) {
if (nextState.open == true && this.state.open == false) {
this.props.onWillOpen();
}
}

componentDidUpdate()

The componentDidUpdate is particularly useful when an operation needs to happen after the DOM is updated and the update queue is emptied. It’s probably most useful on complex renders and state or DOM changes or when you need something to be the absolutely last thing to be executed. A most common use case would be, updating the DOM in response to prop or state changes.

Code Example:
componentDidUpdate(){
this.createGrid()
}
  1. Component UnMounting

The react component undergoes the Unmounting Phase, while the component is deleted/removed from the DOM, and any last updations and functions to be executed while the component is being removed shall be done in the Unmounting phase via the componentWillUnmount() lifecycle method.

The Lifecycle method that go through in the unmounting phase are,

  • componentWillUnmount()

componentWillUnmount()

Here the component is almost done and is going to be removed/deleted. Maybe forever or conditionally like show and remove. Before it goes, it asks if you have any last-minute requests. Here you can cancel any outgoing network requests, or remove all event listeners associated with the component.

Basically, clean up anything to do that solely involves the component.

Code Example
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}

Leave a Reply

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.

Khadar Navaz Khan

More from this Author

Follow Us
TwitterLinkedinFacebookYoutubeInstagram