Can you set the component's state in this method?

Question

In the context of this exercise, introducing the componentDidMount() method, can you set the component’s state in this method?

Answer

Yes, you can set the component’s state in this method, using the setState() method. This is not possible in some other lifecycle methods, such as render(), because calling setState() within them can result in infinite loops.

Calling setState() in componentDidMount() will not end up in an infinite loop, but will just invoke an additional rendering. This additional rendering will not be visible as both of the renders will happen be right before the browser updates the screen, but, one drawback to doing this is that the additional render can take some additional time and cause the site to display slower.

Instead of setting the state initially within componentDidMount(), you may consider setting the initial state in the constructor() method instead.

6 Likes