When value is assigned to components state, why console.log prints the previous state?

I'm sending values of numbers from Numbers component to Main component. Everything is working fine until I set that value in my Main component to that component's state.

var Numbers = React.createClass({
    handleClick: function(number){
        this.props.num(number)
    },
    render: function(){
        return (
            <div>
                <button onClick={this.handleClick.bind(null, 1)}>1</button>
                <button onClick={this.handleClick.bind(null, 2)}>2</button>
                <button onClick={this.handleClick.bind(null, 3)}>3</button>
            </div>
        )
    }
})

var Main = React.createClass({
    getInitialState: function(){
        return {
            number: 0
        }
    },
    handleCallback: function(num){
        console.log("number is right here: " + num);
        this.setState({
            number: num
        })
        console.log("but wrong here (previous number): " + this.state.number)
    },
    render: function() {
        return (
            <Numbers num={this.handleCallback} />
            //<SomeComponent number={this.state.number} />
        )
    }
});

React.render(<Main />, document.getElementById('container'));

Why is it behaving like this? Second console.log in handleCallback function prints the previous number, not the number which is in num parameter. I need right number to be in my state, because I'm going to send it immediately as an props in my SomeComponent component.

https://jsfiddle.net/69z2wepo/13000/


Solution 1:

From the docs:

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value. There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.

If you want to print the change after a call to setState, use the optional callback parameter:

this.setState({
    number: num
}, function () {
    console.log(this.state.number);
});

Solution 2:

The setState method is asynchronous, so the new state is not there yet on console.log call. You can pass a callback as a second parameter to setState and call console.log there. In this case the value will be correct.

Solution 3:

Probably because the console.log is triggered before the new state has been really set.

You should use the function:

componentDidUpdate: function() {
    console.log(this.state.number);
}

This function is triggered each time the state is updated.

Hope it helps