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

292
Views
why setInterval inside useEffect hook in React keeps running?

I have this React component

import React, {useEffect, useRef, useState} from 'react';

export default function MyD3(props) {

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

  useEffect(() => {
    
    console.log("first log")

    const interval = setInterval(() => {
      console.log('This will run every second!');
    }, 1300);

    console.log("second log")

    return () => clearInterval(interval);

  },[]);

    return (
      <div >
        <p>{count}</p>
      </div>
    );
  }

I would like to understand why the code inside setInterval keeps running.

When component mounts for the firs time logs first log and second log

are printed in browser console, just one time.

What surprises me it's that, nonetheless the useEffect code is not repeated, the

This will run every second!

keeps been printing.

What I want to know is why, I expected it to be scoped to useEffect only, so that leaving useEffect code would also interrupt the execution of the interval.

I am not clearly understanding how react / js stack works.

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

0

The useEffect code will execute at every render of the react component you are creating. In this case, as you stated [] as the useEffect dependencies, your code will be executed in the first render. Where the interval is going to begin.

That interval is going to keep running endlessly until the component is unmounted. Why? Because the function () => clearInterval(interval); is known as the cleanup function and it is only going to be executed only when the component is, as mentioned before, unmounted. Here is a link to a further explanation

And when is a component unmounted? You can find here a link to a question in this same site which solves this question

about 4 years ago · Juan Pablo Isaza Report

0

hope you are alright! If I understand correctly you would like the setInterval function to stop returning. However you are putting into useEffect with this setting: useEffect(() => {}, []); So everything inside it will be mounted whenever the component is mounted, similar to componentDidMount. So it will always be executed when loading the component.

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!