Home > Mobile >  why setInterval inside useEffect hook in React keeps running?
why setInterval inside useEffect hook in React keeps running?

Time:10-28

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.

CodePudding user response:

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

CodePudding user response:

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.

  • Related