Passing an update function allows you to access the current state value inside the updater. Since setState
calls are batched, this lets you chain updates and ensure they build on top of each other instead of conflicting:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | incrementCount() { this.setState((state) => { // Important: read `state` instead of `this.state` when updating. return {count: state.count + 1} }); } handleSomething() { // Let's say `this.state.count` starts at 0. this.incrementCount(); this.incrementCount(); this.incrementCount(); // If you read `this.state.count` now, it would still be 0. // But when React re-renders the component, it will be 3. } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.