Sobes.tech
Middle

There is a React component where clicking a button twice calls setState with the boolean value inverted. Will it work correctly? What is batching in React?

sobes.tech AI

Answer from AI

If in a React component you call setState twice on a button click to invert a boolean value, the result can be unexpected if you use the setState form with an object directly. This is because React may batch multiple setState calls into one, and the state does not update immediately but asynchronously.

For example, if you have a state const [flag, setFlag] = useState(true), and you call:

setFlag(!flag);
setFlag(!flag);

both calls use the same value of flag, for example true, and both will set it to false, so the state will not change twice, only once.

To correctly invert the state multiple times in a row, you should use the functional form of setState, which takes the previous state:

setFlag(prev => !prev);
setFlag(prev => !prev);

In this case, the first call inverts true to false, and the second back to true.

Batching in React is a mechanism where multiple setState calls made within a single event or update cycle are combined into one component update. This improves performance by avoiding unnecessary re-renders. In React 18, batching works not only inside event handlers but also in asynchronous callbacks.

Therefore, when using multiple consecutive setState calls, it is important to use the functional update form to avoid errors caused by batching.

There is a React component where clicking a button… - sobes.tech