React component’s lifecycle.

Osmel Mora
Jun 22, 2016 · 6 min read
www.123rf.com

A journey to the React components internals.

In previous posts we covered the basics of React and how to build more complex interfaces composing components. In this post we will continue exploring the features of React’s components. Specifically, the component’s lifecycle.

Initialization

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

Mounting

Mounting is the process that occurs when a component is being inserted into the DOM. This phase has two methods that we can hook up with: componentWillMount() and componentDidMount().

getInitialState: function() {...},componentWillMount: function() {
console.log('componentWillMount');
},
...

Updating

There are also methods that will allow us to execute code relative to when a component’s state or properties get updated. These methods are part of the updating phase and are called in the following order:

...
componentWillReceiveProps: function(newProps) {
this.setState({count: newProps.initialCount});
},
...
  • render()
  • componentDidUpdate()
...
componentWillUpdate: function(nextProps, nextState) {
console.log('componentWillUpdate', nextProps, nextState);
},
...
  1. prevState: the previous state object

Unmounting

In this phase React provide us with only one method:

...
componetWillUnmount: function(){
$(this._ref).select2('destroy');
},
...

Conclusions

React gives us the possibility when creating components to declare methods that will be called automatically in certain occasions throughout the component’s lifecycle. Now we have a clear understanding of the role that each component’s lifecycle method plays and the order in which they are called. This gives us the opportunity to perform certain actions when the component is created and destroyed. It also allows us to react to props and state changes accordingly, to easily integrate third-party libraries and to tackle performance optimization problems.

React Ecosystem

All about React and its ecosystem

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store