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

I need some help in identifying the bug in my code.

The precise time mode is not updating every 100 milliseconds.
Where did I go wrong?
Can anybody please help me?

1 Like

You seem to have a typo on line 36. Instead of newDate() it should be new Date(). That should do the trick :slight_smile:

4 Likes

Danke!!
Got it now.
Much appreciated.

2 Likes

hi every one p^lease can someone explain me what mean this line of code in task 3 specially the if condition:

if (this.props.isPrecise === prevProps.isPrecise) {
  return;
}
```ihad understanding the mounting and unmounting method but the update i hadn't understand
2 Likes

To what I understand:

if (this.props.isPrecise === prevProps.isPrecise) {
  return;
}

This code check ifs isPrecise has changed by comparing it to prevProps.

If it’s true, the return statement to stop now and don’t do the next steps.

When a return statement is used in a function body, the execution of the function is stopped.
If specified, a given value is returned to the function caller.
If the value is omitted, undefined is returned instead.