React and setState

Hi, in this lesson, you create a game of chance, and increment a counter to see how many times the user has played.

Part of the code involves

handleClick() {
this.setState({
counter: this.state.counter +1 // change code here
});
}

However, in a previous lesson, and in that post , it is advised to use a function in the setState function like so :

handleClick() {
this.setState(state => ({
counter: this.state.counter +1 // change code here
}));
}

Is it a (small) issue with the lesson, or is my understanding of the setState function incorrect ?

Both ways are correct in their own way. Check this to know more.

I don’t understand why the first way would be correct. In the first case, the counter is not guaranteed to be up to date, according to the React docs

The function handleClick() should be binded to the constructor to work.
Or you can declare the function in the constructor itself.

Regarding React Docs, checkout this where they use the same method as in the first case.

It’s just not guaranteed to be correct. It often doesn’t matter that a value is not the most up to date – it will be most of the time, occasionally it won’t be :man_shrugging:t3:.