Skip to main content
setInterval in React Components

React Hooks: setInterval in React Components

This article will demonstrate how to invoke the setInterval() method as soon as your component is displayed on the screen or when a user clicks a button.

We’ll create a functional component and use hooks to demonstrate it.

Why Do We Use SetInterval

SetInterval makes it possible to run a function at predetermined intervals. In React projects, it’s frequently quite helpful for things like periodically requesting data or testing a condition.

The setInterval() method return interval ID and you can store the intervalId into the state value.

Simple Example Of SetInterval

Let’s use a setInterval in a functional React component. We are using setInterval() method into the useEffect() method.

useEffect(() => {
  const interval = setInterval(() => {
    console.log('This will be called every 1 second');
  }, 1000);
}, []);

The above code is print the phrase: “This will be called every 1 second” every second to the console until it is cleared.

With the help of the useEffect Hook, the code above schedules a new interval to execute once per second. The React component will schedule this after its initial mounting. By returning clearInterval from the useEffect Hook and supplying the interval as an argument, the interval is properly cleared.

How To Clear Interval

A function or block of code that is bound to an interval executes until it is stopped. To stop an interval, you can use the clearInterval() method.

useEffect(() => {
  const interval = setInterval(() => {
    console.log('This will be called every 1 second');
  }, 1000);

  return () => clearInterval(interval);
}, []);

The scheduled interval is given into the clearInterval method that the useEffect function returns. As a result, after the component unmounts from the DOM, the interval is correctly cleared and no longer triggers every second.

setInterval() on button click

You must place the setInterval() method call inside the button’s onClick event handler property if you want the setInterval() method to run when the user clicks a button.

handleClick = () => {
    const newIntervalId = setInterval(() => {
		console.log("test...");
      });
    }, 1000);
}

Side Effect Of setInterval in React

You can create numbers of setIntervals running into your application. This could seriously slow down your app and memory leak.

Leave a Reply

Your email address will not be published. Required fields are marked *