I found a behavior where the generator appears to be called twice.
The following is a simple code that gets a number from the generator and output it to console. It expects 0 and 1 to be output to the console, but in fact it outputs 0 and 2.
import { useState, useEffect } from "react";
function* counter() {
let val = 0;
while (true) yield val++;
}
const count = counter();
function App() {
console.log("rendered: count = ", count.next().value);
const [hoge, setHoge] = useState("first");
console.log("rendered:", hoge);
useEffect(() => setHoge("second"), [setHoge]);
return <div>{hoge}</div>;
}
export default App;
demo: https://codesandbox.io/s/friendly-http-g84cp?file=/src/App.tsx
Not only to useEffect
, I also found the same behavior with setInterval
. Also, if we remove <React.strict>, the console outputs 0 and 1 as expected.
Do you have any idea why this behavior is happening?
setHoge
in dependency array ofuseEffect
? it should behoge
useEffect
checks the state variable not state updater function(setHoge
).