In a previous blog post, I covered the Javascript functions setInterval and setTimeout. Using setInterval is pretty straightforward and particularly helpful for automating certain functions and features, but what if you need to use in React?
Before we being, feel free to brush up on or learn setInterval in my previous post here –> https://alejandrolinan.home.blog/2020/07/10/settimeout-and-setinterval-javascript/
In vanilla Javascript, probably for a static application, you would setInterval in this manner.
const countUp = setInterval(sayHi, 1000)
function sayHi(){
console.log('Hi!')
}
function stopGreeting(){
clearInterval(countUp)
}
Basically, the countUp variable calls the function sayHi every second, and to stop this the stopGreeting function, when called, will stop the countUp variable. It does this because the interval is set within a variable and is then updated. Easy to do because it’s all within the same file and same component. However, in React, where we have multiple components and moving parts, i.e. compDidMount(), compWillMount(), render(), etc, where do we store this single variable that can be accessed from anywhere within this component?
The short answer, is the state, the longer answer requires a demonstration. Let’s build a simple timer. All we have here is a number counting up by 1, every 1 second. We also include a button to stop the timer when clicked.
Basic code setup

What we see

Simple enough, now let’s add some functions that will update our state when called and start our interval when called!

updateTime simply updates the state.time by incrementing the number by one. setTimeInterval calls the updateTime function every second. clearTimeInterval would clear our state.interval when called. Inside our componentDidMount lifecycle we call setTimeInterval so that when the page mounts the timer begins! Here’s what that looks like!
As you can see, it increments by one every second, and when the button is clicked, the time stops. You can the file code here.

Conclusion
Setting and clearing an interval isn’t hard as long as you know to store the value in the state where it can accessed from any lifecycle or function within a component.