This following onClick callback function will cause 1 re-render:
const handleClickSync = () => {
// Order of setters doesn't matter - React lumps all state changes together
// The result is one single re-rendering
setValue("two");
setIsCondition(true);
setNumber(2);
};
React lumps all three state changes together and causes 1 rerender.
The following onClick callback function, however, will cause 3 re-renderings:
const handleClickAsync = () => {
setTimeout(() => {
// Inside of an async function (here: setTimeout) the order of setter functions matters.
setValue("two");
setIsCondition(true);
setNumber(2);
});
};
It's one re-render for every useState
setter. Furthermore the order of the setters influences the values in each of these renderings.
Question: Why does the fact that I make the function async (here via setTimeout
) cause the state changes to happen one after the other and thereby causing 3 re-renders. Why does React lump these state changes together if the function is synchronous to only cause one rerender?
You can play around with this CodeSandBox to experience the behavior.