Table of contents
1.
Introduction
2.
NPM & Node JS
2.1.
What is Node.js?
2.2.
What is NPM?
2.2.1.
Example: Installing React Using NPM
3.
Why Node.js and NPM are Important for React
3.1.
React JS
3.1.1.
Key Features of React
4.
JavaScript setTimeout
4.1.
Syntax
4.2.
Example
5.
React JS Hooks
5.1.
Common Hooks
6.
What is setTimeout?
6.1.
Using setTimeout in React Components
6.2.
Example: Using setTimeout to Display a Message
7.
Clearing setTimeout
7.1.
How to Clear setTimeout
7.2.
Example
8.
Frequently Asked Questions
8.1.
Why do we need to clear setTimeout in React?
8.2.
Can we use setTimeout without useEffect in React?
8.3.
What is the difference between setTimeout and setInterval?
9.
Conclusion
Last Updated: Jan 26, 2025
Medium

How to Use setTimeout in React

Author Sinki Kumari
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

setTimeout is a built-in JavaScript function that allows you to delay the execution of a function or code block for a specified amount of time. In React, setTimeout is commonly used to introduce delays in actions such as animations, API calls, or state updates. While using setTimeout in React, it's important to manage side effects properly, especially when working with state or components that may unmount before the timeout completes.

How to Use setTimeout in React

In this article, we will discuss how the setTimeout function is used in React. You will learn about its purpose, how to use it with React components, and the importance of clearing timeouts to avoid memory leaks. We will also learn concepts like Node.js, NPM, React Hooks, and the JavaScript setTimeout function to give you a well-rounded understanding. 

NPM & Node JS

What is Node.js?

Node.js is a runtime environment that allows developers to run JavaScript code outside the browser. It is widely used in React development to manage dependencies and create development servers.

What is NPM?

NPM (Node Package Manager) is the default package manager for Node.js. It allows you to install libraries like React and manage project dependencies.

Example: Installing React Using NPM

npm install react react-dom


This command installs React and ReactDOM in your project. Make sure you have Node.js installed before running it.

Why Node.js and NPM are Important for React

Both Node.js and NPM are essential because they:

  • Allow you to create a React project quickly using tools like create-react-app.
     
  • Manage dependencies efficiently.
     
  • Provide a development server for testing your application.

React JS

React JS is a JavaScript library developed by Facebook. It helps in building reusable UI components and managing the state of applications. React uses a component-based structure, which makes it easy to maintain and scale projects.

Key Features of React

  1. JSX: A syntax extension for writing HTML within JavaScript.
     
  2. Virtual DOM: Improves app performance by updating only the required parts of the real DOM.
     
  3. Component-based architecture: Encourages code reusability.
     

Here’s a simple example of a React component:

import React from 'react';
function Greeting() {
    return <h1>Hello, World!</h1>;
}
export default Greeting;


This component renders a heading that says "Hello, World!".

JavaScript setTimeout

The setTimeout function in JavaScript is used to execute a task after a specified delay. It takes two arguments:

  1. A callback function to execute.
     
  2. The delay in milliseconds.

Syntax

setTimeout(callback, delay);

Example

setTimeout(() => {
    console.log('This message is displayed after 2 seconds');
}, 2000);


Output

"This message is displayed after 2 seconds"

React JS Hooks

Hooks are functions that let you use state and lifecycle features in functional components.

Common Hooks

  1. useState: Manages state in functional components.
     
  2. useEffect: Handles side effects like API calls and timers.
     

Here’s an example of the useState and useEffect hooks:

import React, { useState, useEffect } from 'react';
function Counter() {
    const [count, setCount] = useState(0);

    useEffect(() => {
        console.log(`Count updated: ${count}`);
    }, [count]);

    return (
        <div>
            <p>Count: {count}</p>
            <button onClick={() => setCount(count + 1)}>Increment</button>
        </div>
    );
}
export default Counter;


This component increments a counter and logs the updated count to the console.

What is setTimeout?

setTimeout is a built-in JavaScript function that runs code after a specified time. It’s particularly useful in React for tasks like showing a loading spinner or creating animations.

Using setTimeout in React Components

To use setTimeout in React components, you typically call it inside lifecycle methods or hooks like useEffect. Here’s an example:

Example: Using setTimeout to Display a Message

import React, { useState, useEffect } from 'react';

function DelayedMessage() {
    const [message, setMessage] = useState('');

    useEffect(() => {
        const timer = setTimeout(() => {
            setMessage('Hello after 3 seconds!');
        }, 3000);

        return () => clearTimeout(timer); // Cleanup timeout
    }, []);

    return <h1>{message}</h1>;
}

export default DelayedMessage;


Explanation

  1. setTimeout: Sets a delay of 3 seconds to update the message state.
     
  2. clearTimeout: Ensures the timeout is cleared when the component unmounts, preventing memory leaks.
     

Output: Displays "Hello after 3 seconds!" after a 3-second delay.

Clearing setTimeout

Clearing setTimeout is crucial to prevent issues like:

  • Unintended behavior when a component unmounts.
     
  • Memory leaks in your application.

How to Clear setTimeout

Use the clearTimeout function with the timer ID returned by setTimeout.

Example

import React, { useEffect } from 'react';
function TimerComponent() {
    useEffect(() => {
        const timer = setTimeout(() => {
            console.log('Timer executed');
        }, 5000);

        return () => {
            clearTimeout(timer);
            console.log('Timer cleared');
        };
    }, []);

    return <h1>Check the console for messages</h1>;
}

export default TimerComponent;


Output:

  1. If the component unmounts within 5 seconds, "Timer cleared" is logged.
     
  2. Otherwise, "Timer executed" is logged after 5 seconds.

Frequently Asked Questions

Why do we need to clear setTimeout in React?

Clearing setTimeout prevents memory leaks and ensures the timeout doesn’t execute after a component has unmounted.

Can we use setTimeout without useEffect in React?

While you can use setTimeout directly, it’s better to use it inside useEffect to manage side effects properly.

What is the difference between setTimeout and setInterval?

setTimeout executes a task once after a delay, while setInterval executes it repeatedly at specified intervals.

Conclusion

In this article, we discussed about setTimeout function and its use in React components. We started by discussing NPM, Node.js, and React basics, followed by an introduction to the JavaScript setTimeout function. We discussed how to use setTimeout in React components and the importance of clearing timeouts to avoid memory leaks. 

Live masterclass