1

based on the https://stackoverflow.com/a/73115899/21769004 and the example from https://legacy.reactjs.org/docs/hooks-state.html, below is valid code:

import React, { useState } from 'react';

function App() {

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

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

What if I click the button twice very quickly, so first click calls setCount(count + 1) and because React's state change apply asynchronously, so count is still 0 (after the first click) at the moment, then I click the button again within 5 millisecond, and the second click calls setCount(count + 1), since the first update hasn't been applied, so the count still 0, and the second click uses the stale count value, therefore it shows "You clicked 1 times" instead of "You clicked 2 times".

Is my understand correct? is the reason that we still get correct results because we cannot make a consecutive click within tiny millisecond, but theoretically if we can make consecutive clicks faster enough then the code could be a bug?

lch
  • 125
  • 7
  • Are you programmatically firing the click? – evolutionxbox Aug 02 '23 at 14:55
  • 3
    That's why you should use the callback version of setState, `setCount(c => c + 1)`, – Keith Aug 02 '23 at 14:59
  • @Keith but the react hooks's offical docs doesn't use the callback, and based on the answer https://stackoverflow.com/a/73115899/21769004, it doesn't need to use callback for a single handler call – lch Aug 02 '23 at 23:17
  • @evolutionxbox no, but it doesn't sound right when the arise of bugs depends on how fast you click the button – lch Aug 02 '23 at 23:19
  • Regardless, the callback version takes scope out of the equation.. And if your like me, I like to refactor, so not having to worry about scope is a bonus. – Keith Aug 03 '23 at 01:47

1 Answers1

0

The React take of this using Batching.

Batching in React describes the internal implementation detail of React which treats multiple state updates as one state update. The benefit: multiple state updates are batched as one state update and therefore trigger only one re-rendering of the component which improves the rendering performance.

So, without batching, frequent clicks can lead to unnecessary re-renders and potentially incorrect UI display in certain scenarios. It can also result in performance issues and reduced efficiency.

You can read more about this concept here.

Himanshu Verma
  • 131
  • 1
  • 10