简体   繁体   中英

SetTimeout in component executing twice in react

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

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);
}, []);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM