Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • React Tutorial
  • React Exercise
  • React Basic Concepts
  • React Components
  • React Props
  • React Hooks
  • React Router
  • React Advanced
  • React Examples
  • React Interview Questions
  • React Projects
  • Next.js Tutorial
  • React Bootstrap
  • React Material UI
  • React Ant Design
  • React Desktop
  • React Rebass
  • React Blueprint
  • JavaScript
  • Web Technology
Open In App
Next Article:
Re-rendering Components in ReactJS
Next article icon

Using setTimeouts in React Components

Last Updated : 29 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

Prerequisites:

  • NPM & Node JS
  • React JS
  • JavaScript setTimeout
  • React 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.

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

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



Next Article
Re-rendering Components in ReactJS
author
codesaurav
Improve
Article Tags :
  • Technical Scripter
  • Web Technologies
  • ReactJS
  • Technical Scripter 2022
  • React-Questions

Similar Reads

  • Timeline Component in React.js
    Timelines are often used in user interfaces to illustrate a step-by-step procedure. It can describe to the user which stage of the process they currently are and what the further tasks are. Material UI labs module provide a Timeline component along with some other utility components to make this ver
    3 min read
  • Re-rendering Components in ReactJS
    Re-rendering is an important concept in ReactJS as it determines how and when components update. Understanding the re-rendering process is essential for optimizing the performance of React applications. What is Re-rendering in ReactJS?In React, a re-render happens when a component's state or props c
    5 min read
  • Event Countdown Timer Using React
    Event Countdown Timer is an application where you can create an event with the name, date, and category of the event and it will create a card that will show you the remaining time of the event. After reaching that time of the day it will notify you. The application will provide the option to start,
    5 min read
  • ReactJS UI Ant Design Statistic Component
    Ant Design Library has this component pre-built, and it is very easy to integrate as well. Statistic Component is used when we want to display statistic numbers. It can be used in applications that have to display statistic data like games applications for scores, cricket scores website, etc. We can
    3 min read
  • Accessing state in setTimeout React.js
    We frequently deal with timeouts when developing different applications with React. A setTimeout method enables us to invoke a function after a particular interval. However, implementing the conventional setTimeout in React can be difficult. Prerequisites:NodeJS or NPMReact JSsetTimeoutSteps to Crea
    3 min read
  • React Native Smart Components
    In this article, we are going to learn about Smart components in React Native. The smart component is one of the categories of React Components so before diving into the smart components detail. A Component is one of the core building blocks of React and React-Native. The component is a block of cod
    3 min read
  • React Suite Tooltip Component
    React Suite is a popular front-end library with a set of React components that are designed for the middle platform and back-end products. Tooltip component allows the user to display informative text when users hover over, focus on, or tap an element. We can use the following approach in ReactJS to
    3 min read
  • Are Class Components Still Useful in React?
    Class components in React are the traditional method for creating components, utilizing ES6 class syntax. They manage state and lifecycle methods within a class structure. State Management: Class components handle state internally using this.state and update it with this.setState().Lifecycle Methods
    4 min read
  • ReactJS UI Ant Design TimePicker Component
    Ant Design Library has this component pre-built, and it is very easy to integrate as well. TimePicker Component is used to select a time from a popup panel when the user clicks on the input box. We can use the following approach in ReactJS to use the Ant Design TimePicker Component. TimePicker Props
    3 min read
  • How to update the state of react components using callback?
    The state is mutable in react components. To make the React applications interactive we almost use state in every react component. The state is initialized with some value and based on user interaction with the application we update the state of the component at some point in time using setState met
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences