O'Reilly logo

Mastering React by Ryan Vice, Adam Horton

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Component lifecycle - 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.

var HelloMessage = React.createClass({
    componentWillMount: function() {
        console.log('componentWillMount');
    },
    componentDidMount: function() {
        console.log('componentDidMount');
    },
    componentWillUnmount: function() {
        console.log('componentWillUnmount');
    },
    render: function() {
        console.log('render');
        return <h2>{this.props.message}</h2>;
    }
});

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

  • componentWillMount ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required