Jose Alejandro Duque
Jose Alejandro Duque

Reputation: 37

Accessing component state in react

I am interested in understanding why setting a components state (setState()) is slow to update i.e. I may read an old value after the fact that I called setState(). Additionally i am interested in knowing if reading the component state also incurs a penalty to know if I should minimize the number of reads/writes to component state. I tried looking for the documentation at the react website but no dice. Thanks

Upvotes: 1

Views: 55

Answers (2)

Madhuri
Madhuri

Reputation: 1100

React batch multiple setState() calls into a single update for performance. Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state. https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous

Upvotes: 1

VersifiXion
VersifiXion

Reputation: 2282

setState() is asynchronous, so you won't get the new value in the same function where you update it

Upvotes: 1

Related Questions