I saw in the ReactJS docs that the dependency array in useEffect(fn, [])
is optional, and not supplying it should be the same as supplying an empty array.
However, if I have the code as on: https://codesandbox.io/s/trusting-sunset-h6ip9?file=/src/Count.js
useEffect(() => {
console.log("SETTING INTERVAL");
setInterval(() => {
console.log("NOW", Date.now() / 1000);
setDuration(Date.now() - startTime);
}, 1000);
}, []);
With the []
above, everything runs as expected. However, if I remove it and run again, as can be seen on: https://codesandbox.io/s/dreamy-platform-l93bv?file=/src/Count.js
We can see in the Developer's console or Codesandbox.io's console that the line "SETTING INTERVAL"
is continuously being printed.
Supposedly, I thought having the empty array and not having in should make no difference, but in this case we need to put it in? What is the reason?