React 18 Bug: Updaters are NOT called twice for the first time when in Strict Mode
Hi @ssmkhrj, I'd like to share my perspective as to why those behaviours take place. In all cases, I've simply added a Let's see what happens in the first CodeSandbox app( const handleClick = () => {
setCount((count) => {
debugger;
console.log("Clicked");
return count + 1;
});
};
Looking at the call stack, we can see A few things worth mentioning:
From the above image, notice that So, since Next, when React eventually determines the new value to be displayed, it will check first if if (update.hasEagerState) {
// If this update is a state update (not a reducer) and was processed eagerly,
// we can use the eagerly computed state
newState = ((update.eagerState: any): S);
} else {
const action = update.action;
newState = reducer(newState, action);
}
and if that's the case, it won't invoke the function provided to On subsequent times, because My take on this is that React works properly - the Let's now see the second example, which uses React 18 + const reducer = (count, incrementor) => {
debugger;
log("Reducer ran");
return count + incrementor;
};
From the call stack we can see that However, an interesting fact is that both hooks(
But, since if (update.hasEagerState) {
// If this update is a state update (not a reducer) and was processed eagerly,
// we can use the eagerly computed state
newState = ((update.eagerState: any): S);
} else {
const action = update.action;
newState = reducer(newState, action);
}
and this why the console logs twice on each click. The As you can see, there is no both
I'd say things work as expected since the I don't know if the fact that |