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:

React.useEffect(() => {
    const callback = () => {
        console.log('delayed message...');
    };
    const handle = setTimeout(callback, 1000); // called after 1 second
    return () => clearTimeout(handle);
}, []);

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

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

// ONLINE-RUNNER:browser;

// import React from 'react';
// import ReactDOM from 'react-dom';

const App = () => {
    React.useEffect(() => {
        const callback = () => {
            console.log('some message...');
        };
        const handle = setTimeout(callback, 1000);  // called after 1 second
        return () => clearTimeout(handle);
    }, []);
    return (
        <div>Component body here...</div>
    );
};

const root = document.querySelector('#root');
ReactDOM.render(<App />, root);

 

Reusable hook example

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.

// ONLINE-RUNNER:browser;

// import React from 'react';
// import ReactDOM from 'react-dom';

const useTimeout = (callback, timeout) => {
    const ref = React.useRef();
    ref.current = callback;
    React.useEffect(() => {
        const handle = setTimeout(() => ref.current?.(), timeout);
        return () => clearTimeout(handle);
    }, [timeout]);
}


// Usage example:

const MyComponent = () => {
	useTimeout(() => console.log('some message...'), 1000);
    return (
      <div>Component body here...</div>
    );
};

const App = () => {
    const [visible, setVisible] = React.useState(false);
    return (
      <div>
        <button onClick={() => setVisible(true)}>Mount MyComponent</button>
        <button onClick={() => setVisible(false)}>Unmount MyComponent</button>
        {visible && <MyComponent />}
      </div>
    );
};

const root = document.querySelector('#root');
ReactDOM.render(<App />, root);

 

See also

  1. React - useEffect hook

References

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

Alternative titles

  1. React - setTimeout & clearTimeout
  2. React - setTimeout with useEffect hook
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