setState or setState(func), that is the question
Davide Cerbo
1

First and foremost: Never mutate state directly. Even in setState (no matter whether you’re using the object or the function parameter).

Second:

So, the second setState will enqueued and will start when the first setState will end.

You have no guarantee on setState calls being queued or not. Actually, you have a guarantee, but this guarantee differs depending on the context you call setState from.

If you call setState from within React (Lifecycle methods, event handlers on elements rendered by React) setState calls will be batched and executed at a later time. This is true for both, the object and functional setState.

If you call setState from outside React (setTimeout, event handlers on actual DOM nodes (e.g. document.addEventListener(…)) setState will be executed the moment you call it.

class MyComponent extends Component {
constructor() {
this.state = {foo: 0};
}

componentDidMount() {
document.addEventListener('click', () => {
this.setState({foo: this.state.foo + 1}};
this.setState({foo: this.state.foo + 1}};
console.log(`Foo is now ${this.state.foo}`); // Foo is now 2
}
}
}

The advantage of functional setState is that your callback is guaranteed to receive the current state after the previous callbacks have done their job. It basically works like this:

applyStateUpdates () {
this.state = this.batchedUpdates.reduce((newState, update) => {
if (isFunction(update)) {
return Object.assign({}, newState, update(newState));
}
return Object.assign({}, newState, update);
}, this.state);
}
One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.