-1

Originally I was going to title this, Is componentDidMount() Better than useEffect with dependency array []?

I have two different react projects.

Project A was made using version "react": "^16.14.0",

Project B was made with version "react": "^18.2.0",

in Project A I used componentDidMount mostly for performing state change/api pulls/ etc and console.log on top to make sure the componentDidMount life-cycle ran only onces.

in Project B I am using useEffect to perform similar actions, and again I have a console.log right on top to make sure the useEffect (life cycle) runs only one... it does not, it runs TWICE. And I am very very confused Why on Earth would it be run twice? Has anyone else ran into such an issue? The code is a very simple console.log

  React.useEffect(()=>{
    console.log("app()")
  },[])

I Expect it to run ONLY ONCE, but it runs twice.

Additionally, I even have a useMemo with the dependency which console.log twice instead of once. I am certain my implementation is correct. The code works, the UI displays data as expected.

As a matter of fact EVERY Console.log is running twice in Project B . Has anyone else run into an issue where they get Extra console.log, and how did you resolve it?

Thx

adnan tariq
  • 197
  • 2
  • 13

1 Answers1

3

This is because of React.StrictMode. In development mode only, it will mount every component twice to help catch accidental impurities in your code.

Unmitigated
  • 76,500
  • 11
  • 62
  • 80
  • thank you @Unmitigated Yes it is running on StrikeMode. And your saying this will happen in dev mod only but will never happen in deployment? How do I turn off as i find this feature annoying to work with. – adnan tariq Jan 26 '23 at 15:43
  • @adnantariq Yes, this is only to help during development. Each component will only be mounted once in production. – Unmitigated Jan 26 '23 at 15:43