You get a bonus - 1 coin for daily activity. Now you have 1 coin

Why do we need to pass a function to setState()? in REACT

Practice



The reason for this is that

setState()
is an asynchronous operation. React batches state changes for performance reasons, so the state may not change immediately after a
setState()
call. This means you should not rely on the current state when calling
setState()
since you cannot be sure what that state will be. The solution is to pass a function to
setState()
with the previous state as an argument. By doing this, you can avoid the problem of the user getting an old state value on access because of the asynchronous nature of
setState()
.

Let's say the initial value of a counter is zero. After three consecutive increment operations, the value will only be incremented by one.

// assuming this.state.count === 0
this.setState({ count: this.state.count + 1 })
this.setState({ count: this.state.count + 1 })
this.setState({ count: this.state.count + 1 })
// this.state.count === 1, not 3
If we pass a function to setState()
, the count will be incremented correctly.
created: 2020-02-23
updated: 2026-03-09
219



Was this answer useful?
Choose a quick rating so we can improve the next answer for you.
How satisfied are you?


Comments

To leave a comment

If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Lectures and tutorial on "Scripting client side JavaScript, jqvery, BackBone"

Terms: Scripting client side JavaScript, jqvery, BackBone