React – How to queue a series of State Updates?

https://react.dev/learn/queueing-a-series-of-state-updates

What is “queue the next render”?

What is the result of this code when you click on the button once?

import { useState } from 'react';

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>
    </>
  )
}

It’s not 3 but 1, why? Because React waits until all code in the event handlers has run before processing your state updates. Each render’s state values are fixed, so the value of number inside the first render’s event handler is always 0

setNumber(0 + 1);
setNumber(0 + 1);
setNumber(0 + 1);

How to update the same state multiple times before the next render?

...
      <button onClick={() => {
        setNumber(n => n + 1);
        setNumber(n => n + 1);
        setNumber(n => n + 1);
      }}>+3</button>
...

n => n + 1 is called an updater function:

  1. React queues this function to be processed after all the other code in the event handler has run.
  2. During the next render, React goes through the queue and gives you the final updated state

React works through these lines of code while executing the event handler:

  1. setNumber(n => n + 1)n => n + 1 is a function. React adds it to a queue.
  2. setNumber(n => n + 1)n => n + 1 is a function. React adds it to a queue.
  3. setNumber(n => n + 1)n => n + 1 is a function. React adds it to a queue.
queued updatenreturns
n => n + 100 + 1 = 1
n => n + 111 + 1 = 2
n => n + 122 + 1 = 3

So the result after one click is 3

What happens if you update state after replacing it?

<button onClick={() => {
  setNumber(number + 5);
  setNumber(n => n + 1);
}}>
  • setNumber(number + 5)number is 0, so setNumber(0 + 5). React adds replace with 5 to its queue.
  • setNumber(n => n + 1)n => n + 1 is an updater function. React adds that function to its queue.
queued updatenreturns
“replace with 50 (unused)5
n => n + 155 + 1 = 6

Result is 6

What happens if you replace state after updating it?

<button onClick={() => {
  setNumber(number + 5);
  setNumber(n => n + 1);
  setNumber(42);
}}>
  1. setNumber(number + 5)number is 0, so setNumber(0 + 5). React adds replace with 5 to its queue.
  2. setNumber(n => n + 1)n => n + 1 is an updater function. React adds that function to its queue.
  3. setNumber(42): React adds “replace with 42 to its queue.
queued updatenreturns
“replace with 50 (unused)5
n => n + 155 + 1 = 6
“replace with 426 (unused)42

Result is 42

Be the first to comment

Leave a Reply

Your email address will not be published.


*