How to set a timeout in React (with examples)

July 27, 20211 min read


Using setTimeout lets you execute a function after a specific amount of time elapsed. It's often very useful in React apps, for example when working with animations.

The code

Let's get straight to the code. This is how you use setTimeout in a functional React component:

useEffect(() => {
  const timeout = setTimeout(() => {
    console.log('This will be called after 2 seconds');
  }, 2000);

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

If you want a detailed explanation on how this works, you can check out the setInterval article which works basically the same way!

Package versions at the time of writing

Did you enjoy this article?

If so, a quick share on Twitter could really help out!