This is the 23rd 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
  • React State update queue (3) – Use the updater function or any value to change the state difference

Naming conventions

The updater function argument is usually named with the first letter of the corresponding state variable:

setEnabled(e= >! e); setLastName(ln= > ln.reverse());
setFriendCount(fc= > fc * 2);
Copy the code

If you prefer more detailed code, another common convention is to repeat the full state variable names, such as setEnabled(enabled =>! Enabled), or use the prefix setEnabled(prevEnabled =>! PrevEnabled).

conclusion

  • Setting state does not change a variable in an existing render, but it does change in a new render.
  • React handles state updates after the event handler has finished running. This is called batch processing.
  • To update a status multiple times in an event, you can usesetNumber(n => n + 1)Update program functions.

Practice – Fix the request counter

You are developing an art market application that allows users to submit multiple orders for a work of art simultaneously. Each time the user presses the “Buy” button, the “Pending” counter should increase by one. After three seconds, the “Pending” counter should decrease and the “Completed” counter should increase.

However, the “Pending” counter does not behave as expected. When you press “Buy”, it is reduced to -1 (this should be impossible!). . If you click twice quickly, both counters seem to behave unpredictably.

Why does this happen? Fix two counters.

import { useState } from 'react';

export default function RequestTracker() {
  const [pending, setPending] = useState(0);
  const [completed, setCompleted] = useState(0);

  async function handleClick() {
    setPending(pending + 1);
    await delay(3000);
    setPending(pending - 1);
    setCompleted(completed + 1);
  }

  return (
    <>
      <h3>
        Pending: {pending}
      </h3>
      <h3>
        Completed: {completed}
      </h3>
      <button onClick={handleClick}>
        Buy     
      </button>
    </>
  );
}

function delay(ms) {
  return new Promise(resolve= > {
    setTimeout(resolve, ms);
  });
}
Copy the code

3

2

1

In the handleClick event handler, the values of pending and Completed correspond to their values at the time the event was clicked. For the first render, pending is 0, so setPending(pending-1) becomes setPending(-1), which is incorrect. Since you want to increase or decrease counters, rather than setting them to specific values determined during a click, you can pass the updater function instead:

import { useState } from 'react';

export default function RequestTracker() {
  const [pending, setPending] = useState(0);
  const [completed, setCompleted] = useState(0);

  async function handleClick() {
    // This function
    setPending(p= > p + 1);
    await delay(3000);
    setPending(p= > p - 1);
    setCompleted(c= > c + 1);
  }

  return (
    <>
      <h3>
        Pending: {pending}
      </h3>
      <h3>
        Completed: {completed}
      </h3>
      <button onClick={handleClick}>
        Buy     
      </button>
    </>
  );
}

function delay(ms) {
  return new Promise(resolve= > {
    setTimeout(resolve, ms);
  });
}
Copy the code

This ensures that when counters are added or subtracted, they are added or subtracted based on their latest state, not their state at click time.