By Ran Bar-Zik | 11/16/2018 | General |Beginners

The React Lifecycle

The React Lifecycle

In the last article, we took an in-depth look at events inside of React components and how to manage them, thereby managing the state as well. When we learned about stateful components we looked at componentDidMount which was activated when the component was ready. But where does the method come from? We’re talking about a series of methods that are called for the entire life of the component—from its creation until its death.

 

We can use these methods for our needs; most of the time we use them for communicating with other components. For instance, if I have a parent component (which I generally do), there’s a chance that it will want to know when the child component is updated. If I want to do this, I need to call a certain function inside the React lifecycle.

lifecycle pic

So long story short, it’s something that you really should be familiar with. While it’s true that when we write simple components we mostly use componentDidMount, this isn’t always the case. If we have validations, calls to an API, or components that die (are unmounted), we’ll have to know about the ‘lifecycle’: the list of functions that are called from the components beginning to its end.

 

So, how shall we demonstrate this? We’ll simply create a component that has the lifecycle in it i.e. the entire list of functions that are called according to the appropriate moment in the life of the component. OK, here’s some code:

<div id='content'></div>
<script type='text/babel'>
   class Counter extends React.Component {
     render() {
       const textStyle = {
         color: 'black',
         fontSize: 72,
         fontWeight: 'bold'
       };

       return (
         <div style={textStyle}>
           {this.props.display}
         </div>
       );
     }
   }

   class CounterParent extends React.Component {
     constructor(props, context) {
       super(props, context);
       console.log('constructor: Default state time!');

       this.state = {
         count: 0
       };

       this.increaseCounter = this.increaseCounter.bind(this);
     }

     increaseCounter() {
       this.setState({
         count: this.state.count + 1
       });
     }

     componentWillUpdate(newProps, newState) {
       console.log('componentWillUpdate - Component is about to update!');
     }

     componentDidUpdate(prevProps, prevState) {
       console.log('componentDidUpdate - Component just updated!');
     }

     componentWillMount() {
       console.log('componentWillMount - Component is about to mount soon!');
     }

     componentDidMount() {
       console.log('componentDidMount - Component just mounted!');
     }

     componentWillUnmount() {
       console.log('componentWillUnmount - Component is about to be deleted');
     }

     shouldComponentUpdate(newProps, newState) {
       console.log('shouldComponentUpdate - Testing if component should update...');

       if (newState.count < 4) {
         console.log('shouldComponentUpdate - Component should update!');
         return true;
       } else {
         ReactDOM.unmountComponentAtNode(target);
         console.log('shouldComponentUpdate - Component should not update!');
         return false;
       }
     }

     componentWillReceiveProps(newProps) {
       console.log('componentWillReceiveProps - Component will get new props!');
     }

     render() {
       const backgroundStyle = {      
         border: 'black 3px dotted',
         borderRadius: 12,
         padding: 20,
         textAlign: 'center',
         width: 250,
       };

       return (
         <div style={backgroundStyle}>
           <Counter display={this.state.count} />
           <button onClick={this.increaseCounter}>+</button>
         </div>
       );
     }
   };

   console.log('defaultProps - Default prop insertion!');
   CounterParent.defaultProps = {

   };

const target = document.getElementById('content');
ReactDOM.render(
 <CounterParent />,
 target
);
</script>

CounterParent is the component in which we put the console.log in order to see the various calls. Here, check out this demo that I wrote and have a look at your console.log. Click on the plus sign and notice what happens. The component kills itself when the counts get higher than three.

component lifecycle in react

The first thing we see is constructor: Default state time!. And if you look at the code you’ll see it appears in the constructor. This is the first thing that happens. The code is loaded and ready to run. The second thing to happen is componentWillMount which is pretty self-explanatory. The end is componentDidMount which we’re already familiar with.

 

The next stages happen when I update the state. For this to occur we need to click on the button which can cause a few interesting things to happen with shoudComponentUpdate—I can now understand that the component is about to update. Notice I use this function to kill it if the counter gets to four. Try clicking on it and take note of the rest of the events. There are explanations of all of the events in the official React documentation. Notice that there are changes between different versions. Here we’re using version 16, but in version 17 the events componentWillMount, componentWillReceiveProps, and componentWillUpdate are not present—they’re simply disappeared. From version 1.3 and up we’ll receive alerts about such events.

 

I can’t emphasize enough the importance of the lifecycle when it comes to developing components—it’s used constantly in complex components. For instance, if I want to execute a call to AJAX and populate the data of a subcomponent but only if they’ve changed, then the React lifecycle is critical. If I need to act in accordance with events or changes that occur in child components, again, the lifecycle is a must. So it’s really quite important that you understand it. Go into the demo, check out the code there, and try to grasp that it’s possible to join and run code with every action in a component.

 

Previous Article: React Components with Events Next article: React and the DOM

 

 About the author: Ran Bar-Zik is an experienced web developer whose personal blog, Internet Israel, features articles and guides on Node.js, MongoDB, Git, SASS, jQuery, HTML 5, MySQL, and more. Translation of the original article by Aaron Raizen. 

By Ran Bar-Zik | 11/16/2018 | General

{{CommentsModel.TotalCount}} Comments

Your Comment

{{CommentsModel.Message}}

Recent Stories

Top DiscoverSDK Experts

User photo
3355
Ashton Torrence
Web and Windows developer
GUI | Web and 11 more
View Profile
User photo
3220
Mendy Bennett
Experienced with Ad network & Ad servers.
Mobile | Ad Networks and 1 more
View Profile
User photo
3060
Karen Fitzgerald
7 years in Cross-Platform development.
Mobile | Cross Platform Frameworks
View Profile
Show All
X

Compare Products

Select up to three two products to compare by clicking on the compare icon () of each product.

{{compareToolModel.Error}}

Now comparing:

{{product.ProductName | createSubstring:25}} X
Compare Now