class Hello extends React.Component {
constructor(props){
super(props)
this.state={count:1};
this.myRef = React.createRef();
}
use(){
console.log(this.myRef);
let f=function(){
this.setState({count:2});
console.log("in f" + this.state.count);
}
//let a=React.findDOMNode(this.myRef.current);
this.myRef.current.onclick=f.bind(this);
//console.log(a);
}
render() {
console.log("in render"+" "+this.state.count);
return (
<div>Hello {this.state.count}
<div onClick={this.use.bind(this)}>add function</div>
<button ref ={this.myRef}>click</button>
</div>;
)
}
}
ReactDOM.render(
<Hello name="World" />,
document.getElementById('container')
);
In this code 'console.log("in f" + this.state.count)' is executing after 'console.log("in render"+" "+this.state.count)' that is possible only if setState is synchronous function call that internally calls another synchronous function render.But according to reactjs setState is asynchronous ,so 'console.log("in f" + this.state.count)' should be executed first.Why it is behaving like this?