SetTimeout in component executing twice in react

Viewed 245

When I render the App component the code inside setTimeout runs twice.

I saw that setTimeout runs after the call stack has finished executing. I don't know whether its relevant to this.

Is it something to do with how react renders components.

index.js

import { StrictMode } from "react";
import ReactDOM from "react-dom";

import App from "./App";

const rootElement = document.getElementById("root");
ReactDOM.render(
  <StrictMode>
    <App />
  </StrictMode>,
  rootElement
);

App.js

import "./styles.css";

export default function App() {
  
  setTimeout(() => {
    console.log(`Logged!`);
  },
  1000
  )
  
  return (
    <div className="App">
      <h1>Hello</h1>
    </div>
  );
}
1 Answers

Your setTimeOut is called on every render of the App component.

In your case, React.StrictMode causes the re-renders.

To prevent this, you can add it in a useEffect hook with an empty dependency array:

useEffect(() => {
  const timer = setTimeout(() => {
    console.log(`Logged!`);
  }, 1000);
  return () => clearTimeout(timer);
}, []);
Related