0

I am having a hard time understanding how useEffect works. Like the code below, The count1 inside setInterval will always be 0 and useEffect never reaches the count2. Meaning, after the first render, useEffect runs and it goes inside setInterval and never leaves, so how does the count in h1 still get updated? If it never gets out of useEffect. I thought state changes will always trigger a re-render thus trigger another useEffect. Maybe I am missing something. Please help. Thank you!

import { useState, useEffect } from "react";
import ReactDOM from "react-dom";

function Timer() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    setInterval(() => {
      setCount((count) => count + 1);
      console.log("count1" + count);
    }, 1000);
    console.log("count2" + count);
  }, []);

  return <h1>I've rendered {count} times!</h1>;
}

export default Timer;
Dinh Minh Luu
  • 71
  • 4
  • 7
  • Take a look at this https://stackoverflow.com/questions/57542264/how-to-setinterval-for-every-5-second-render-with-react-hook-useeffect-in-react – Posandu Dec 21 '21 at 10:20
  • There are plenty duplicates https://stackoverflow.com/questions/65489257/react-setinterval-behavior/65489303#65489303 – Dennis Vash Dec 21 '21 at 10:23

2 Answers2

0

The important thing to note here is that count is a local variable.

Every time the Timer function gets called, it has a new count variable belonging to that invocation (which gets assigned a value by useState.

The first time the Timer function is called, the useEffect runs and the arrow function passed to setInterval forms a closure around that instance of count.

So every time the interval ticks, it logs the same value of count.


Meanwhile the callback function passed to setCount gets the latest value of count from the state, so it can be incremented there.

If you had just done: setCount(count + 1); then you would be reading the closed over count and constantly setting it to 0 + 1.


And time Timer gets called it has a new count with the latest value stored in the state.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

The things you should fix:

DirectionUnkown
  • 203
  • 3
  • 9