This is the 20th day of my participation in the November Gwen Challenge. Check out the details: The last Gwen Challenge 2021

Translate: beta.reactjs.org/learn/queue…

Setting the value of state causes another Render queue. But sometimes you may want to perform multiple operations on the value before executing the next Render queue. To do so, this article helps you understand how React updates status in batches.

You will learn:

  • What is “batching” and how does React handle multiple state updates
  • How do I apply several updates to the same state in one line

React Updates the state in batches

You might think that clicking the “+3” button would increase the counter’s value three times, since it calls setNumber(number + 1) three times:

export default function Counter() {
  const [number, setNumber] = useState(0);

  return (
    <>
      <h1>{number}</h1>
      <button onClick={()= >{ setNumber(number + 1); setNumber(number + 1); setNumber(number + 1); }} > + 3</button>
    </>)}Copy the code

However, as you may recall from earlier, the state value for each render is fixed, so the number value in the event handler for the first render is always 0, no matter how many times you call setNumber(1) :

setNumber(0 + 1);
setNumber(0 + 1);
setNumber(0 + 1);
Copy the code

But there is another factor to discuss. React waits for all the code in the event handler to run before processing the state update. That’s why rerendering only happens after all these setNumber() calls.

It might remind you of a waiter ordering food at a restaurant. The waiter doesn’t run to the kitchen as soon as he hears your first order! Instead, they let you complete your order, let you modify it, and even accept other people’s orders at the table.

This allows you to update multiple state variables — even from multiple components — without triggering too much rerender. But this also means that the UI is not updated until the event handler and any code in it is complete. This behavior, also known as batch processing, makes your React application run faster. It also avoids dealing with confusing “half-finished” renderings, only some of which are updated.

React does not batch across multiple intended events (such as clicks) — each click is handled individually. Rest assured, React only does bulk processing when it is generally safe. This ensures, for example, that if a button is disabled the first time, a second click won’t resubmit it.