Piotr Berebecki Piotr Berebecki - 2 months ago 13
Javascript Question

Alert invoked in React JS componentDidMount lifecycle method pops up before the initial render instead of after

I'm going through the Codecademy React JS course: https://www.codecademy.com/courses/react-102/lessons/mounting-lifecycle-methods/exercises/componentdidmount

The lesson explains the basics of the React lifecycle mounting methods ordering them as follows: componentWillMount -> render -> componentDidMount.

This codepen demonstrates the problem: http://codepen.io/PiotrBerebecki/pen/vXyYKP

The issue is that according to the instructions the alert included in the

componentDidMount
method (saying: 'YOU JUST WITNESSED THE DEBUT OF... FLASHY!!!!!!!') should pop up after the red text is rendered on the screen. However when I test it, the alert actually pops up before the text is rendered. Is this the expected behaviour?

Full code:

var Flashy = React.createClass({
componentWillMount: function() {
alert('AND NOW, FOR THE FIRST TIME EVER... FLASHY!!!!');
},

componentDidMount: function() {
alert('YOU JUST WITNESSED THE DEBUT OF... FLASHY!!!!!!!');
},

render: function() {
alert('Flashy is rendering!');
return (
<h1 style={{ color: this.props.color }}>
OOH LA LA LOOK AT ME I AM THE FLASHIEST
</h1>
);
}
});

ReactDOM.render(
<Flashy color='red' />,
document.getElementById('app')
);

setTimeout(function() {
ReactDOM.render(
<Flashy color='green' />,
document.getElementById('app')
);
}, 2000);

Answer

It is actually working as expected.

But the alert function prevents the DOM rendering

You can actually try it with console.log which works in the background.

Take a look of this codepen http://codepen.io/joseaplwork/pen/xERkaG

Make sure to open the inspector, I also added a debugger statement in order to see when componentDidMount is called