React, Use State to Toggle an Element

In a previous lesson, they say you can change the state by passing an object to the setState method, but now they jumped to functions, can someone explain more please! and why we shouldn’t use this in this lesson, thank you in advance! :grinning: :heart:

Hi @bedward.

The reason of passing a callback to setState is right there in the explanation. React state updates can sometimes occur asynchronously.

Sometimes you might need to know the previous state when updating the state. However, state updates may be asynchronous - this means React may batch multiple setState() calls into a single update. This means you can’t rely on the previous value of this.state or this.props when calculating the next value. So, you should not use code like this:

1 Like