why does my setInterval is not working in React app Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of why does my setInterval is not working in React app without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I’m new to react and I’m trying to create a simple time showing website for practice
I tried using setInterval() but it’s not working.

Here’s my App.js file

import React from "react";
import "./style.css";

function Clock(props) {
  return (
    <>
      <h2>{props.date.toLocaleTimeString()}</h2>
    </>
  );
}

function App() {
  return (
    <div>
      <Clock date={new Date()} />
    </div>
  );
}

setInterval(App, 1000);  {/* setInterval(Clock, 1000) */}

export default App;

and Index.js file

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

import App from "./App";

ReactDOM.render(<App />, document.getElementById("root"));

Answer

Calling a functional component alone doesn’t do anything unless you put the resulting element into a ReactDOM.render or into another functional component. Your setInterval(App, 1000); is doing nothing.

Have the component get itself to rerender instead.

function App() {
  const [date, setDate] = useState(new Date());
  useEffect(() => {
    setInterval(() => {
      setDate(new Date());
    }, 1000);
  }, []);
  return (
    <div>
      <Clock date={date} />
    </div>
  );
}

Then the single use of ReactDOM.render(<App />, document.getElementById("root")); will result in the clock updating whenever the state changes.

If you ever plan on unmounting the component, it’d also be good to save the interval ID in a variable and return a cleanup function from the effect callback to clear the interval.

  useEffect(() => {
    const intervalId = setInterval(() => {
      setDate(new Date());
    }, 1000);
    return () => clearInterval(intervalId);
  }, []);
We are here to answer your question about why does my setInterval is not working in React app - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji