Youwang Deng

I'm a software developer, familiar with C#, Java, JavaScript, focus on full stack development.

React Native setState not update immediately

13 Jun 2019 » JavaScript, React, React-Native

Sometimes, after setState in react native or react, then use console.log to check the state, the state is not updated, that’s due to the mechanism of React.

According to the documentation:

setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall. Instead, use componentDidUpdate or a setState callback (setState(updater, callback))

this.setState({someKey: keyValue}, ()=>{
    alert(this.state.someKey);
});