How To Clear A Timeout Or An Interval In React Hooks?

Clear a timeout or an interval in React with hooks

If you don’t know how to clear a timeout or an interval in React hooks, don’t worry. Learn more about it with the explanation and examples below.

How setTimeout() and setInterval() work ?  

setTimeout()

The setTimeout() function in JavaScript is used to execute a specified function or piece of code only once after a certain period.

Syntax:

setTimeout(function, milliseconds)

Code:

function helloWorld() {
  console.log('Hello World');
}
setTimeout(helloWorld, 1000);

The program will execute the HelloWorld function after 1s, and ‘Hello World’ will be displayed only once.

Note: If the parameter delay is omitted or not specified, the value 0 (default) will be used, meaning that the defined function is only executed immediately or as soon as possible.

setInterval()

Similarly, you can use the setInterval() function to execute a specified function or code repeatedly at fixed intervals.

Syntax:

setInterval(function, milliseconds, param1, param2, ...)

Code:

function helloWorld() {
  console.log('Hello World');
}
setInterval(helloWorld, 1000);

The program will execute the HelloWorld function each 1s, and ‘Hello World’ will be displayed an infinite number of times.

The difference between setTimeout() and setInterval()

The only difference between them is setTimeout fires the expression only once, while setInterval fires the expression after a specific time (unless you stop it).

React hooks: Clear a timeout or an interval

How to clear a timeout

First, you should know about clearTimeout(). The clearTimeout() method clears the timer using the setTimeout() method.

Syntax:

clearTimeout(var)

Code:

import { useEffect, useState } from "react";
export default function App() {
  const [visible, setVisible] = useState(false);
  useEffect(() => {
    const visibleTimeout = setTimeout(() => {
      setVisible(true);
    }, 1000);
    return () => {
      clearTimeout(visibleTimeout);
    };
  }, []);
  return (
    <div>
      {visible? (
          <h1>Visible = true</h1>
      ) : (
          <h1>Visible = false</h1>
      )}
    </div>
  )

In this example, we registered a timeout using setTimeout(), so it will set the state visible from false to true after one second. When the component unmounts, we clear the timeout.

How to clear an interval

The clearInterval() method is used to clear the task we have set up in the setInterval() method.

Syntax:

clearInterval(var)

Code:

import {useEffect, useState} from 'react';
export default function App() {
  const [timer, setTimer] = useState(0);
  useEffect(() => {
    const timerInterval = setInterval(() => {
      setTimer(prev => prev + 1);
    }, 1000);
    return () => {
      clearInterval(timerInterval);
    };
  }, []);
  return (
    <div>
      <h2>Timer: {timer}s</h2>
    </div>
  );
}

Just like the example with the timeout, we also use the clear interval method to remove the interval we created.

Summary

To summarize, this article shows you how to clear a timeout or an interval in React hooks. Specifically, here we use the useEffect hook and take advantage of component unmounting.

Maybe you are interested:

Leave a Reply

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