I have the following problem.
function App() {
const [state, setState] = useState({ a: 0 });
const handleClick = () => {
Promise.resolve().then(() => {
const _state = { a: 1 };
console.log("1");
setState(_state);
console.log("2");
_state.a = 2;
setState(_state);
console.log("3");
_state.a = 3;
setState(_state);
});
};
return (
<div>
<button onClick={handleClick}>Test</button>
<br />
{console.log("render", state)}
{state.a}
</div>
);
}
After I click the button, following output is shown in the console:
1
render {a: 1}
2
render {a: 2}
3
But it renders {a: 1}
instead of {a: 2}
So at the end state is changed and its value is {a: 3}
, but react doesn't render new value.In react devtools I can clearly see state: {a: 3}
.
If I remove Promise.resolve
the code will work as expected.
Additional question is, why does it invoke render in the middle of the code (after console.log(1)
?
Here is the full example: https://codesandbox.io/s/exciting-platform-0j45u