Author -  Sai gowtham

How to use the setTimeout in React Hooks

In this tutorial, we are going to learn about the usage of setTimeout function in React hooks with the help of examples.

What is a setTimeout function?

The setTimeout() function is used to invoke a function or a piece of code after a specified amount of time is completed.

Example:

setTimeout(() => {
    console.log('you can see me after 2 seconds')
}, 2000);

Using the setTimeout in React hooks

We can use the setTimeout function in React hooks just like how we use in JavaScript.

In this example, we have used the setTimeout function inside useEffect hook to update the count value from 0 to 1 after a 3000 milliseconds (or 3 seconds) is finished.

App.js
import React, { useState, useEffect } from "react";

export default function App() {
  const [count, setCount] = useState(0);

  useEffect(() => {
   const timeout = setTimeout(() => {      setCount(1);    }, 3000);  },[]);

  return (
    <div className="App">
      <h1>{count}</h1>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

Note: we have passed empty array [] as a second argument to the useEffect hook so that it only runs when a App functional component is initially rendered into the dom, it is similar like componentDidMount in class components.

Clearing setTimeout

To clear the setTimeout, we need to call the clearTimeout method by passing our timeout variable as an argument.

App.js
import React, { useState, useEffect } from "react";

export default function App() {
  const [count, setCount] = useState(0);

  useEffect(() => {
   const timeout = setTimeout(() => {
      setCount(1);
    }, 3000);

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

  return (
    <div className="App">
      <h1>{count}</h1>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

Note: returning a function inside useEffect hook is like using a componentWillUnmount() lifecycle method inside class-based react components.

If you want to run a setTimeout function whenever a component state is updated, you need to pass the condition to an empty array [].

App.js
import React, { useState, useEffect } from "react";

export default function App() {
  const [count, setCount] = useState(0);

  useEffect(() => {
   const timeout = setTimeout(() => {
      setCount(1);
    }, 3000);

   return () => clearTimeout(timeout);
  },[count]);
  return (
    <div className="App">
      <h1>{count}</h1>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

Here we passed count as a condition to the array so that setTimeout function runs initially and also when a count value is changed.

setTimeout in Class components

This example shows you, how to use the setTimeout in class-based react components.

Counter.js
import React from "react";

class App extends React.Component {
  state = {
    count: 0
  };

  componentDidMount() {
    this.timeout = setTimeout(() => {      this.setState({ count: 10 });    }, 3000);  }

  handleIncrement = () => {
    this.setState({ count: this.state.count + 1 });
  };

  componentWillUnmount() {
    clearTimeout(this.timeout);  }

  render() {
    return (
      <div className="App">
        <h1>{this.state.count}</h1>
        <button onClick={this.handleIncrement}>Increment</button>
      </div>
    );
  }
}

export default App;

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2023 (Beginner + Advanced)
JavaScript - The Complete Guide 2023 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY