Asynchronous

The setState function should always be considered asynchronous, as the official documentation says:

"There is no guarantee of synchronous operation of calls to setState [...]"

If we try to log the current value of the state into the console after we fire setState in an event handler, we get the old state value:

  handleClick() { 
this.setState({
clicked: true,
});

console.log('the state is now', this.state);
}

render() {
return <button onClick={this.handleClick}>Click me!</button>;
}

For example, the preceding snippet now renders the state as null.

Into the console. The reason this happens is that React knows how to optimize the state update inside event handlers and it batches the operation for better performance.

However, if we change our code a little as follows:

  handleClick() { 
setTimeout(() => {
this.setState({
clicked: true
});

console.log('the state is now', this.state);
});
}

The result is going to be as follows:

  the state is now Object {clicked: true}

This is what we may have expected in the first place, and it's because React does not have any way to optimize the execution and it tries to update the state as soon as possible.

Please notice that setTimeout has been used in the example only to show the behavior of React, but you should never write event handlers in that way.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.166.122