Ever wonder why React's setState doesn't update immediately?

vatana7

vatana7

Posted on March 18, 2023

Ever wonder why React's setState doesn't update immediately?

Yesterday I was browsing new React's website react.dev that includes up-to-date documentation and tutorials out of boredom. While browsing, I have come across this section called Queueing a Series of State Updates and it sparked an interest in me. After reading, I have learned something new from it.

Now I always knew that React doesn't instantly update state when you tell it you to do so. I always knew this in the back of my head but never really knew what is happening inside the hood.

Here's an example:

  const [count, setCount] = useState(0);

  const handleClick = () => {
    setCount(count + 1);
    setCount(count + 1);
    setCount(count + 1);
  };

// For somebody who just started to learn React you might 
// think that count would be 3 right? Nope
Enter fullscreen mode Exit fullscreen mode

It turns out that React will waits for the codes inside the event handlers to finish before processing your state updates and then re-render. React calls it batching. For an analogy, it's like a waiter is waiting for you to make all your orders then run to the kitchen to give it to the cook.
In React's context, it means React will wait until you call a bunch of setState then group it together and make a single re-render to improve performance. This process is called batching.

So in order to immediately update the state multiple times before next render, you can React's Updater Function.

const [count, setCount] = useState(0);

const handleClick = () => {
    setCount(count + 1);
    setCount((count) => count + 1); // called updater function
    // next render count = 2
 };
Enter fullscreen mode Exit fullscreen mode

Here's a psuedocode to demonstrate how React's queue work inside the hood.

let count = 0 //Initial value
const queue = [
setCount(count + 1), // return count = 1
setCount(count => count + 1)  // return count as 1+1 = 2
]
rerender()
Enter fullscreen mode Exit fullscreen mode

So if you want to simultaneously update the state without waiting for the next render you can use Updater Function to make it happen.

In conclusion, today we have learnt that React has an operation called batching that take multiple setState call and wait to execute it at once for improvement. And we also learn how to update state immediately using Updater Function without waiting for next render as well. I hope you learn something new today!

Thank you!

đź’– đź’Ş đź™… đźš©
vatana7
vatana7

Posted on March 18, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related