Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

125
Views
Different behaviour of setInterval in react vs vanilla javascript

I have been experimenting with setInterval. Both the codes were executed in Chrome. Below is my react component

function App() {
  let [value, setValue] = useState(0);

  useEffect(() => {
    const id = setInterval(() => console.log(value), 1000);

    return () => clearInterval(id);
  }, []);

  return (
    <div className="App">
      <p>{value}</p>

      <button onClick={() => setValue(value + 1)}>+</button>
      <button onClick={() => setValue(value - 1)}>-</button>
    </div>
  );
}

The console.log in setTimeout inside useEffect keeps printing 0 no matter how many times you increment or decrement the value via button click.

Following code is being executed in browser (Chrome) console

let value = 0;

setInterval(() => console.log(value), 1000);

value = 3; // can be considered as setValue (sort of)

Now the browser console prints 3 which is expected.

I wonder why there is a difference in behaviour and would appreciate if someone could point out the reason for this. Any other code snippet or link that demonstrate this even better would be great.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You need to pass value as a dependency to your useEffect. Unless you give the list of items that your effect dependent upon in the dependency array, it will keep using the initial value.

  useEffect(() => {
    const id = setInterval(() => console.log(value), 1000);

    return () => clearInterval(id);
  }, [value]);
about 4 years ago · Juan Pablo Isaza Report

0

İn your example useEffect only work once when page loaded. This is why you only get console.log(0). If you want to make it when value change you need specify that in useEffect

For example

UseEffect(() =>{ console.log(value) }, [value])

In your example when you click to button, first value sets after that useEffect works and setInternals function triggered after 1s.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!