2

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 Answers1

2

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);
}, []);
SLePort
  • 15,211
  • 3
  • 34
  • 44
  • His component only renders once. https://codesandbox.io/s/thirsty-dhawan-iyv1t?file=/src/App.js Can you explain why the `setTimout` callback is triggered twice? – codemonkey Feb 15 '21 at 07:09
  • 2
    @codemonkey Because of the `StrictMode` I guess. Two `console.log('Logged!")` with it, one without it. – SLePort Feb 15 '21 at 07:14
  • 1
    Yep! You should put that in your answer, because that's what the OP wants to know. – codemonkey Feb 15 '21 at 07:15