Languages
[Edit]
EN

React - setTimeout example

0 points
Created by:
Dragontry
731

In this article, we would like to show you setTimeout method example in React

Quick solution:

setTimeout() is a method that takes in two arguments:

  • a function which is being called after amount of time (timeout),
  • the timeout time (in milliseconds).

setTimeout() is waiting to be executed until it's cancelled by clearTimeout() method which takes the handle to the timeout that has been already set as an argument.

Below we present some practical examples for better understanding.

 

Simple setTimeout example

Edit

In this example we use useEffect() hook to run the callback() function inside it when the App component is first rendered. The useEffect() returns a clearTimeout() function, which means it will be executed when it is time to clean up (on App component unmount).

 

Reusable hook example

Edit

In this example, we create a reusable useTimeout component that takes two arguments:

  1. callback - a function to be executed once the timeout timer expires,
  2. timeout - the timer time in milliseconds.

We use the custom setTimeout in MyComponent to display some text in the console after 1000 milliseconds (1 second) on the component mount.

 

See also

Edit
  1. React - useEffect hook

References

Edit
  1. setTimeout() - Web APIs | MDN
  2. clearTimeout() - Web APIs | MDN

Alternative titles

  1. React - setTimeout & clearTimeout
  2. React - setTimeout with useEffect hook
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join