by Sai gowtham

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.

App.js
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.

setinterval react hooks

Using setInterval in Class components

This example shows you how to use setInterval in class components.

App.js
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.

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
26,545 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
221,520 students enrolled
44 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
114,575 students enrolled
21 hours of video content
View Course