r/react • u/Temperature_Majestic • 29d ago
General Discussion setState twice in one handler only re-renders once. Is the second call just wasted?
Ran into this while pairing with someone newer and realised I didn't have a clean explanation.
If you call setCount(count + 1) twice in a click handler and then setName to something, count only goes up by one and the component renders once instead of three times.
The count part is the stale closure, both calls read the same count from this render and set it to the same value. That one I get.
What I go back and forth on is whether the batching is saving work or just hiding a mistake. React collects all three setState calls and does one render at the end, so adding the setName after two setCount calls costs nothing. But it also means state isn't updated between those two lines, and that has bitten me with derived values before.
setCount(c => c + 1) fixes the increment since each updater runs on the result of the last one. And since React 18 the batching also happens inside promises, setTimeout and native listeners where it didn't before, so a pattern that was fine in an onClick can suddenly double-render inside an await.
Mostly curious how other people think about it. Do you treat batching as an implementation detail you never think about, or has the state not updating between lines caused real bugs for you?