JSFiddle - React, Tailwind, and code Playground
by treekey
HTML
<script src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
<h1>setState race condition example</h1>
<hr>
<div id="app" />
Babel + JSX
class Click extends React.Component {
constructor(props) {
super(props)
this.state = { count: 0 }
this.onClear = this.onClear.bind(this)
this.onClick = this.onClick.bind(this)
this.onClickWithUpdater = this.onClickWithUpdater.bind(this)
}
shouldComponentUpdate(nextProps, nextState){
console.log('shouldComponentUpdate', nextState)
return this.state.count !== nextState.count
}
onClear(e){
this.setState({ count: 0 })
}
onClick(e){
for (let step = 0; step < this.props.times; step++) {
console.log('click!')
this.setState({ count: this.state.count + 1 })
}
}
onClickWithUpdater(e){
for (let step = 0; step < this.props.times; step++) {
console.log('click with updater!')
this.setState((preState) => ({ count: preState.count + 1 }))
}
}
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.onClick}>
Plus {this.props.times} times!
</button>
<br />
<button onClick={this.onClickWithUpdater}>
Plus {this.props.times} times with updater!
</button>
<br />
<button onClick={this.onClear}>Clear</button>
</div>
)
}
}
const App = () => (
<div>
<Click times={1} />
<hr />
<Click times={10} />
</div>
)
ReactDOM.render( <App /> , document.getElementById('app'));