settimeout in react

setTimeout in React Components Using Hook

setTimeout in React using setInterval

A function or code block tied to a space removes until it is suspended. To pause, you can use the clear Interval () method.

For example, the code below sets a new interval when the React object first rises. After the React Reduction period is cleared:

Exaple of setTimeout in React


useEffect(() => {
 const interval = setInterval(() => {
 setSeconds(seconds => seconds + 1);
 }, 1000); 
return () => clearInterval(interval);
}, []);

What is setInterval?

setInterval is a method that calls for work or executes a code after certain intervals, as defined in the second parameter.

Read Also :  How to Use React Context API with Example

For example, the code below sets a print interval for the phrase: “Interval created” every second in console until it is deleted.

Example of setInterval in react


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

function tick() {
  const element = (
      <h1>Hello, world!</h1>
      <h2>It is {new Date().toLocaleTimeString()}.</h2>
  ReactDOM.render(element, document.getElementById('root'));

setInterval(tick, 1000);