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>
  );
}
2

1 Answer 1

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);
}, []);
Sign up to request clarification or add additional context in comments.

3 Comments

His component only renders once. codesandbox.io/s/thirsty-dhawan-iyv1t?file=/src/App.js Can you explain why the setTimout callback is triggered twice?
@codemonkey Because of the StrictMode I guess. Two console.log('Logged!") with it, one without it.
Yep! You should put that in your answer, because that's what the OP wants to know.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.