setState() in React

jad abdallah
2 min readJul 26, 2021

The setState() function is the main way to change your local state in React class components.

While setState() is very useful, it does have one major quirk to be aware of: it’s asynchronous. What this means is that it doesn’t really change the state right when the interpreter reads it.

Instead it ‘enqueues’, or schedules, your intended state change. Only when the call stack is empty will your change be processed.

The call stack is like a local backlog of work the program is aware of but still has to complete, like a person might use a to-do list to help remember all the small jobs needed for a complex task.

As the React docs note, “You can think of setState() as a request rather than an immediate command to update the component. For better perceived performance, React may delay it, and then update several components in a single pass.”

That is, whatever other work had to be done in that function will be executed first, and only then will setState’s changes be enacted in a more sweeping way.

However, this delay can lead to tricky situations. In the image below for example, say you put a console.log(this.state) right under the setState. It would be reasonable to expect it to display your new state, right?

So why can’t you just change the state manually, like with “this.state.allCats = cats” ?

Mainly because then, React won’t know that it should re-render. We should treat the state as immutable, as if it were a const we declared. In fact, not accounting for this issue is a common source of errors when using destructive functions like .sort.

Such functions, which return a changed version of the original object, are not appropriate to use in setState() without taking precautions to avoid state mutation.

For example if you were in a setState method and using .sort() on an array, you could chain .concat([]) onto that array first, so its information would be copied into a brand new array.

Only then would you call .sort, confident in the knowledge that any changes made would not affect the original state object.

--

--