How to use the setInterval in React (including hooks)
In this tutorial, we are going to learn about the usage of setInterval function in react hooks and class based components.
What is a setInterval function?
The setInterval() function is used to invoke a function or a piece of code repeatedly after a specific amount of time.
Example:
setInterval(() => {
console.log('you can see me every 3 seconds')
}, 3000);
The only way to stop the setInterval is by calling a clearInterval function with id or closing the window.
Using setInterval in React hooks
We can use the setInterval function in React, just like how we can use in JavaScript.
In this below example, we using the setInterval
function inside useEffect hook.
import React, { useEffect, useState } from "react";
export default function App() {
const [seconds, setSeconds] = useState(1);
useEffect(() => {
const timer = setInterval(() => { setSeconds(seconds + 1); }, 1000); // clearing interval
return () => clearInterval(timer);
});
return (
<div className="App">
<h1>Number of seconds is {seconds}</h1>
</div>
);
}
The useEffect hook runs the callback function when a component mounts to the dom, which is similar like componentDidMount life cycle method in class components.
The setInterval function runs the setSeconds
method for every one second.
Inside the useEffect hook we are returning a clearInterval function with a timer
argument, so that setInterval function is stopped when a component unmounts from the dom, which is similar like componentWillUnmount method.
You can see the output like this.
Using setInterval in Class components
This example shows you how to use setInterval in class components.
import React from "react";
class App extends React.Component {
state = {
seconds: 1
};
componentDidMount() {
this.timer = setInterval(() => { this.setState({ seconds: this.state.seconds + 1 }); }, 1000); }
componentWillUnMount() {
clearInterval(this.timer); }
render() {
return (
<div className="App">
<h1>Number of seconds is {this.state.seconds}</h1>
</div>
);
}
}
export default App;
In the above example, we are incrementing this.state.seconds
property using the setInterval() function.