Languages
[Edit]
EN

React - setInterval example

0 points
Created by:
Dirask Community
6900

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

Quick solution:

setInterval(() => {
  console.log('This will be called every 1s');
}, 1000);

setInterval is a method that takes in two arguments:

  • a function which is being called every specific amount of time (interval),
  • the interval time (in milliseconds).

setInterval is executed until it's stopped by clearInterval method which takes the interval as an argument.

Below we present some practical examples for better understanding.

1. Simple setInterval example

In this example we use:

  • useState hook - first one to manage the counter as App component's state and the second one to manage buttons disable property,
  • useRef hook - to create a reference that will help us to set and clear the interval,
  • two button elements that trigger:
    • startCounter function - which sets the interval incrementing our counter every 1s (1000 ms),
    • stopCounter - which stops incrementing the counter by calling clearInterval method.

Runnable example:

// ONLINE-RUNNER:browser;

// Note: Uncomment import lines while working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';

const App = () => {
  const [counter, setCounter] = React.useState(0);
  const [counting, setCounting] = React.useState(false);
  const intervalRef = React.useRef();

  const startCounter = () => {
    intervalRef.current = setInterval(() => {
      setCounter((prevCounter) => prevCounter + 1);
    }, 1000);
    setCounting(true);
  };

  const stopCounter = () => {
    clearInterval(intervalRef.current);
    setCounting(false);
  };

  return (
    <div>
      <h2>{counter}</h2>
      <div>
        <button disabled={counting} onClick={startCounter}>Start counter.</button>
        <button disabled={!counting} onClick={stopCounter}>Stop counter.</button>
      </div>
    </div>
  );
};

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

2. setInterval with useEffect example

In this example, we call setInterval mehtod inside useEffect hook. That approach sets a new interval when the App component mounts for the first time. After the App component unmounts the interval is cleared with clearInterval.

Note:

For more information about how the useEffect works check the article - React - useEffect hook.

Runnable example:

// ONLINE-RUNNER:browser;

// Note: Uncomment import lines while working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';

const App = () => {
  const [counter, setCounter] = React.useState(0);

  React.useEffect(() => {
    const interval = setInterval(() => {
      setCounter(counter => counter + 1);
    }, 1000);
    return () => clearInterval(interval);
  }, []);

  return (
    <div>
      <h2>{counter}</h2>
    </div>
  );
};

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

Related posts

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