This is the 22nd day of my participation in the November Gwen Challenge. Check out the event 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

series

This is a series of articles that I hope you can read from the beginning, because the examples will be sequential

  • React State update queue – How to batch state update in event handler
  • React State update queue (2) – Update the same state multiple times before the next render

What happens if you update state after replacing state

In the last two articles, we said that if you use setNumber(n+1) continuously in an event handler, React will only update it once, just like a server does when you order a meal. SetNumber (n => n + 1). Each time, the parameter n is the latest value of the calculation after the last update.

So what happens if we mix these two ways? Take the following example

<button onClick={() = > {
  setNumber(number + 5);
  setNumber(n= > n + 1); }} >Copy the code
import { useState } from 'react';

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

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

After clicking the button, the number is +6. Why?

Here’s what the event handler tells React to do:

  1. setNumber(number + 5)number 是 0So,setNumber(0 + 5)To React“Is replaced by5Add to its queue.
  2. setNumber(n => n + 1): n => n + 1Is an update function. React adds this function to its queue.

During the next rendering, React iterates through the state queue:

Update the queue n The return value.
“Is replaced by5 0(Unused) 5
n => n + 1 5 5 plus 1 is 6

React stores 6 as the final result and returns it from useState.

You may have noticed that setState(x) is actually similar to setState(n => x), but n is not used!

What happens if you replace state after updating state

In contrast to the example above, let’s update state first

<button onClick={() = > {
  setNumber(number + 5);
  setNumber(n= > n + 1);
  setNumber(42); }} >Copy the code
import { useState } from 'react';

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

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

Here’s how React works with these lines of code when executing the event handler:

  1. setNumber(number + 5)numberThe value is0So,setNumber(0 + 5)To React“Is replaced by5Put it in its queue.
  2. setNumber(n => n + 1): n => n + 1Is an update function. React adds this function to its queue.
  3. setNumber(42): the React“Is replaced by42Put it in its queue.

In the next render, React passes the state queue:

Update the queue n The return value
“Is replaced by5 0(Unused) 5
n => n + 1 5 5 plus 1 is 6
“Is replaced by42 6(Unused) 42

React then stores 42 as the final result and returns it from useState.

conclusion

In summary, you can think of what is passed to setNumber state setters in the following way:

  • Update functions, such as n => n + 1, are added to the queue.
  • Any other value (such as the number 5) adds “replace with 5” to the queue and ignores what is already queued.

After the event handler completes, React will trigger a re-rendering. React will process the queue during re-rendering. The updater function runs during rendering, so the update function must be a pure function and return only results. Do not attempt to set state or run other side effects from within them. In strict mode, React runs each updater function twice (but discards the second result) to help you find errors.