I'm new with React and confused with the result below code is giving.
num gets value -1, where I think it should be 100.
useEffect[num] is expected to run first, calling setNum(100) since num is initialized to -1.
Then useEffect[dummy] will run, calling setNum(-1).
I learned that multiple calls to the same setState function are batched together, and only the result from the last call is rendered.
So it seems like setNum(100) will be overwritten by subsequent setNum(-1).
The problem is, if setNum(-1) was processed in the end, it should have called setNum(100) in useEffect[num].
num should be 100, but it's stuck at -1.
Why did my program stop before calling setNum(100) in the end?
Please teach me what I'm missing : async nature of setState or batched updates?
import "./styles.css";
import React, { useState, useEffect } from "react";
export default function App() {
const [num, setNum] = useState(-1);
const [dummy, setDummy] = useState(false);
useEffect(() => {
console.log("setNum : ", num);
if (num === -1) setNum(100);
}, [num]);
// Just to call setNum(-1) separately
useEffect(() => {
console.log("Init dummy : ", dummy);
setNum(-1);
}, [dummy]);
return (
<div className="App">
<div> {num} </div>
</div>
);
}
Here is codesandbox to run the code.
https://codesandbox.io/s/strange-chatelet-3oxy8?file=/src/App.js