Open In App

Using setTimeouts in React Components

Improve
Improve
Like Article
Like
Save
Share
Report

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.

Prerequisites:

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.

Approach:

Using the setTimeout method in react requires the useEffect hook to cover and execute the side effect when the target element is updated or modified. On rerendering the dependency array the side effects are executed and cleared in the end with the useEffect to maintain the efficiency of the application

Let us understand the various ways to implement the setTimeout method in React. 

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:

npx create-react-app spinnner-gfg

Step 2: After the spinner-gfg app is created, switch to the new folder spinner-gfg by typing the command below:

cd spinner-gfg

Project Structure:  

Final Directory

Example 1: We will use the setTimeout method to show a loading spinner for 5 seconds before rendering some data.

  • We will use the useEffect hook with an empty dependency array to create a timeout once the component mounts. 
  • The data state variable stores the content, and the setData function updates the value of the content. 
  •  When the timer expires, the data is displayed, and the isLoading state is set to false.

Javascript




// Filename - App.js
 
import { useState, useEffect } from 'react';
import './App.css'
 
const App = () => {
    const [isLoading, setIsLoading] = useState(true);
    const [data, setData] = useState(null);
 
    useEffect(() => {
 
        // Creating a timeout within the useEffect hook
        setTimeout(() => {
            setData("Welcome to gfg!");
            setIsLoading(false);
        }, 5000);
    }, []);
 
    if (isLoading) {
        return <div className='spinner'>
            Loading.....</div>;
    }
 
    return (
        <div className='container'>
            {data}
        </div>
    );
}
export default App;


CSS




/* Filename - App.js */
 
.spinner,
.container {
    margin: 1rem;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    font-size: 2rem;
}
 
.container {
    border: 2px solid darkGreen;
}


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

npm start

Output: By default, the React project will run on port 3000. You can access it at localhost:3000 on your browser. 

Output: using the setTimeout method to show a loading spinner for 5 seconds before rendering some data:

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.

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;


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;
}


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. 



Last Updated : 30 Nov, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads