Categories
React Answers

How to use setInterval in a React app?

Spread the love

Sometimes, we want to use setInterval in a React app.

In this article, we’ll look at how to use setInterval in a React app.

How to use setInterval in a React app?

To use setInterval in a React app, we call setInterval in the useEffect hook callback.

For instance, we write

import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";

const Clock = () => {
  const [currentCount, setCount] = useState(10);
  const timer = () => setCount(currentCount - 1);

  useEffect(() => {
    if (currentCount <= 0) {
      return;
    }
    const id = setInterval(timer, 1000);
    return () => clearInterval(id);
  }, [currentCount]);

  return <div>{currentCount}</div>;
};

const App = () => <Clock />;

to call useEffect with a callback that calls setInterval to run the timer function every 1000 milliseconds.

We return a function that calls clearInterval with the timer id to clear the timer when currentCount changes.

Conclusion

To use setInterval in a React app, we call setInterval in the useEffect hook callback.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *