How to use setInterval() in a React class component

Farm & Tree

We can call a setInterval in componentDidMount. We should define the interval with a variable when we are doing it correctly, and then clear the interval in componentWillUnmount, but here we will just see how to set up an anonymous interval.

We want to write the setInterval in the proper format, making sure there is a function inside of it. The problem I ran into was I was executing the function inside of the setInterval, and this was causing the function to run only once, and the setInterval to have no function to run on an interval, because all it was given was a result.

Correct way: Pass the desired operation into an anonymous function:

componentDidMount(){
    setInterval( () => {console.log('heyder')}, 1000);
  }

Incorrect way: Pass the desired operation straight into the setInterval:

componentDidMount(){
    setInterval(console.log('heyder'), 1000);
  }

Writing the setInterval in this second manner is what causes the operation to execute immediately, and leaves the setInterval with no function to loop.