Clearing setTimeouts

In the useEffect hook, we can create timeouts on re-renders whenever the component’s state changes. However, this generates new timeouts each time the state changes and can cause performance issues. It is necessary to clear timeouts when they are no longer needed to prevent potential memory leaks.

The setTimeout method creates a timer and queues a callback function to be executed after a specified time has passed. If the timer expires and the callback function is executed, the timeout is completed.

However, if a new timeout is set using the same variable, the previous timeout is canceled and the new timeout is initiated. If a timeout is not canceled when it is no longer required, the callback function may still be executed, even if the component that set the timeout has been unmounted.

This can result in wasted resources and potential bugs, particularly if the callback function has side effects that are no longer relevant.

To avoid this, we can clear the previous timeout before creating a new one using the clearTimeout method. This is important to prevent memory leaks in our application, as the callback for setTimeout may still execute if we don’t clear it when the component unmounts. 

The clearTimeout Method: 

  • clearTimeout cancels the timeouts generated by the setTimeout method.
  • The setTimeout method returns a timeoutId, which is passed to the clearTimeout.
  • The timeoutId identifies a particular timer generated by the setTimeout function.

Syntax: 

clearTimeout(timeoutID)

Here’s an example of how we can clear setTimeouts in React and create timeouts on re-renders: 

Example 2: Displaying a warning message which disappears after a specified time. This exmaple will display a warning for 5 seconds and then hide it by using the setTimeout method. 

  • We will use the useEffect hook to set a timer when the showWarning state is true and to cancel the timer when the component unmounts or the showWarning state changes. 
  • The useEffect hook invokes whenever the component renders, implying that a timer sets every time the component mounts and the showWarning state is true.
  • To cancel the timer when the component unmounts or the showWarning state changes, we need a way to store the timer ID and access it from the useEffect hook’s cleanup function. This is where the useRef hook comes in.
  • The useRef hook allows us to create a mutable ref that persists across re-renders and can be used to store the timer ID. When the component mounts, the timer ID is stored in the current property of the timerId ref. 
  • When the component unmounts or the showWarning state changes, the useEffect hook’s cleanup function is called, which cancels the timer using the timer ID stored in the timerId ref.
CSS
/* Filename - App.css */

.warn {
    margin: 1rem;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    font-size: 1rem;
}

.warningMsg {
    border: 2px solid orangered;
    background-color: rgb(210, 153, 124);
}

.btn {
    border: 2px solid darkGreen;
    border-radius: 10px;
    margin: 1rem;
    cursor: pointer;
}
Javascript
// Filename - App.js

import { useState, useEffect, useRef } from 'react';
import './App.css'

const App = () => {
    const [showWarning, setShowWarning] = useState(false);
    const timerId = useRef(null);

    useEffect(() => {
        if (showWarning) {

            //Creating a timeout
            timerId.current = setTimeout(() => {
                setShowWarning(false);
            }, 5000);
        }

        return () => {
            //Clearing a timeout
            clearTimeout(timerId.current);
        };
    }, [showWarning]);

    function handleClick() {
        setShowWarning(true);
    }

    return (
        <div className='warn'>
            {showWarning && <div className='warningMsg'>
                This is a Warning ⚠️!</div>}
            <button className='btn' onClick={handleClick}>
                Show Warning</button>
        </div>
    );
}
export default App; 

Step to run the application: Run the application by using the following command:

npm start

Output: This output will be visible on the http://localhost:3000/ on the browser window.

Output: Displaying a warning message which disappears after a specified time. 




Using setTimeouts in React Components

The setTimeout method in React enables the execution of a function after a specified time interval. This functionality is pivotal in web development for implementing time-based behaviors, offering a spectrum of applications ranging from user interface enhancements to asynchronous operations.

The setTimeout is a JavaScript method that executes a function after a particular time. This can be useful for creating time-based effects, such as showing a loading spinner for a few seconds before loading new data or hiding a success message after a few seconds.

Similar Reads

Prerequisites:

NPM & Node JSReact JSJavaScript setTimeoutReact JS hooks...

Using setTimeouts in React Components :

We can use the setTimeout method in React components similar to how we deal with it in JavaScript. In React components, the setTimeout method follows the same principles as in Javascript. However, we should take certain caveats into account....

Steps to Create React Application:

Step 1: Make a project directory, head over to the terminal, and create a react app named spinner-gfg using the following command:...

Clearing setTimeouts:

In the useEffect hook, we can create timeouts on re-renders whenever the component’s state changes. However, this generates new timeouts each time the state changes and can cause performance issues. It is necessary to clear timeouts when they are no longer needed to prevent potential memory leaks....