Member-only story

Why Don’t React State Updates Reflect Immediately?

If you think state updates are asynchronous, you are only partially correct

Shubham Khatri
Better Programming
5 min readApr 23, 2021

--

Photo by Sixteen Miles Out on Unsplash

When working with React a lot of people expect state changes to reflect immediately both in a class and functional component with React hooks.

This, however, is not the case.

State updates using this.setState or useState do not immediately mutate the state but create a pending state transition. Accessing state immediately after calling the updater method can potentially return the old value.

There is no guarantee of synchronous operation of state update calls and multiple state updates can be batched for performance reasons.

Why is State Update Async?

State updates alter the virtual DOM and cause re-rendering which may be an expensive operation. Making state updates synchronous could make the browser unresponsive due to huge number of updates.

To avoid these issues a careful choice was made to make state updates async, as well as to batch those updates.

Can I Wait for setState to be Completed Using async-await?

--

--

Shubham Khatri
Shubham Khatri

Written by Shubham Khatri

Software Engineer at Meta | Passionate about Javascript, React and Web Development | Active Stackoverflow contributor

Responses (2)

Write a response