Component Lifecycle in React

Component Lifecycle in React

mounting and unmounting

Components in React have a lifecycle of events that we can easily subscribe to by defining the associated methods on our component definition object. Let’s go ahead and update our previous example to see this feature in action.

HelloMessage Component

Here we have updated our HelloMessage component to log to the console the following three React component lifecycle events:

  • componentWillMount
    • This event will be called right before a component mounts
  • componentDidMount
    • This event will be called right after a component mounts
  • componentWillUnmount
    • This event will be called right before a component unmounts

We are also logging our render method to the console so that we can see when the various lifecycle events occur relative to render.

Let’s also update our HelloReact component to add a button that will reload our HelloMessagecomponent allowing us to see what happens when it unmounts. We’ve added this button to the render method shown in the following code:

And then let us add a reload method to our HelloReact component that will call React.unmountComponentAtNode which will unmount our component. We then call ReactDOM.render to mount our component.

Now let’s go ahead and run the code in JsFiddle and open our browsers debugging tools (F12 in Chrome) so that we can see the console output. After running the code we see the following output:

And as we can see we get a call to componentWillMount right before Render is called and then we get a call to componentDidMount right after render is called. This gives us an opportunity to run code both before and after our render method. Next let’s add a First Name and we can see what happens in the console as shown below:

We get one more call to render but componentWillMount and componentDidMountare not called because our HelloMessage component is already mounted and we are simply causing React to call the HelloMessage.render method. Let’s set a last name and look at the console output:

Probably no surprise here but we find that render is called again but that none of the lifecycle events are called. Next let’s click the Reload button and look at the following output:

Now we see that componentWillUnmount is called as our component is unmounted and then we repeat the same sequence we saw earlier as the component is mounted again.

Thank you!

Leave a comment