r/learnreactjs • • May 28 '24

Difficulty understanding useEffect!

Help me understand why these different implementations of the same component behave the way that they behave.

// This shows time spent, works as expected. Empty dependency array
function Section() {
  let [timer, setTimer] = useState(0);
  useEffect(() => {
    const id = setInterval(() => {
      setTimer((prevTime) => prevTime + 1);
    }, 1000);
    return () => clearInterval(id);
  }, []);
  return <h3>Time on Page: {timer}</h3>;
}

// Doesn't work, don't understand why not? Empty dependency array
function Section() {
  let [timer, setTimer] = useState(0);
  useEffect(() => {
    const id = setInterval(() => {
      setTimer(timer + 1);  // Change from previous
    }, 1000);
    return () => clearInterval(id);
  }, []);
  return <h3>Time on Page: {timer}</h3>;
}

// Works, somewhat understand why, but shouldn't be correct. No array
function Section() {
  let [timer, setTimer] = useState(0);
  useEffect(() => {
    const id = setInterval(() => {
      setTimer(timer + 1);
    }, 1000);
    return () => clearInterval(id);
  });
  return <h3>Time on Page: {timer}</h3>;
}
// Because timer is changing every second, it's re-rendered each second.
setInterval can be replaced by setTimeout since there's a rerender 
and another setTimeout will be executed? 
This should be incorrect because if something else causes a rerender 
then time calculation will get messed up.
2 Upvotes

2 comments sorted by

View all comments

Show parent comment

1

u/void5253 Jun 13 '24

Yup, figured that out a bit ago.