I am trying to figure out when useEffect causes a re-render. I am very surprised by the result of the following example:
https://codesandbox.io/embed/romantic-sun-j5i4m
function useCounter(arr = [1, 2, 3]) {
const [counter, setCount] = useState(0);
useEffect(() => {
for (const i of arr) {
setCount(i);
console.log(counter);
}
}, [arr]);
}
function App() {
useCounter();
console.log("render");
return <div className="App" />;
}
The result of this example is as follows:
I don't know why:
- The component renders only three times (I would have guessed the component would rerender for every call to
setCount+ one initial render - so 4 times) - The counter only ever has two values 0 and 3: I guess, as this article states, every render sees its own state and props so the entire loop will be run with each state as a constant (1, 2, 3) --> But why is the state never 2?


