React - setTimeout example
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:
callback- a function to be executed once thetimeouttimer expires,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);