
If you are React developer as a beginner, you might wonder how setState()
works and behaves, whenever your code doesn’t as you expected. Here are some common mistakes I think a beginner makes every day.
Mistake 1. setState() update state immediately.
Fact: setState() actions are asynchronous. According to the documentation of setState()
,
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.
setState()
updates the state and will lead to re-rendering unless there are no differs from the previous state.
WhatsetState()
does is reconciliation, the process of re-rendering the components tree. This allows us to have multiple calls to setState in a single scope and preventing unnecessary re-renders of the whole tree.
For example, assuming this.state = {turnOn: false}
, you will not see the updated values right after you updated it.

Mistake 2. Changing this.state will cause re-render
fact: You should be using this.setState
function, which will accept an Object
that will be eventually merged into component’s current state. Only this.setState
can cause re-render with new data. It is still possible to update state by changing this.state
, however, it will not trigger re-rendering, and so the state will be inconsistent.

Mistake 3. React will call setState() at-call-time-current-state
fact: setState()
accepts a function as its parameter and react groups or batches setState()
calls into a single call.
A good example of this idea is the following. After all the below calls are completed, this.state.value = 1.

If you want to make the way you expected, pass a function as the first argument of setState, then React will call it with the at-call-time-current state.

Mistake 4. We can use await setState()
Fact: setState() does not return a “promise”. It seems setState()
could return a promise since setState()
acts as asynchronous. However, it does not. React setState()
is a function that mutates the component state. This component state is a variable that stores a certain value or function of a given component. And setState()
is used to update this component state.
For example, the following codes will not work.

If you want to read updated state and then guarantee to trigger execution after the update has been applied, use callbacks instead, since async/await is not going to work.
For example, setState()
can take a callback function as a second argument.

If you are using React Hooks, then you can do the callbacks like the following codes.

Conclusion
setState()
- is Asynchronous
- can have a function as a parameter instead of object
- can accepts a Callback function as a second argument (optional)
- does not return promise
Reference