11

I have a simple useEffect function setup with the brackets like so:

  useEffect(() => {
    console.log('hello')
    getTransactions()
  }, [])

However when I run my app, it prints two hellos in the console. Any idea why?

Even if I add something like this, two hellos print still.

  const [useEffectCalled, setUseEffectCalled] = useState<Boolean>(false)

  useEffect(() => {
    console.log('hello')
    if (!useEffectCalled) {
      getTransactions()
    }
    setUseEffectCalled(true)
  }, [])
cormacncheese
  • 1,251
  • 1
  • 13
  • 27
  • Maybe something in `getTransactions` is causing a complete re-loading (or remounting) of the component, triggering it once again? Comment it out and see if it still triggers twice, try to locate where the problem is exactly. – cSharp Apr 12 '22 at 00:17
  • @cSharp commented out `getTransactions` just including the `console.log` in useEffect and same thing, logged two hellos...strangest thing – cormacncheese Apr 12 '22 at 00:18
  • 4
    Is your app using Strict Mode? – Joel Hager Apr 12 '22 at 00:31
  • Even if it is in strict mode, useEffect with no dependency, will only run once unless your component remounts. – vighnesh153 Apr 12 '22 at 03:11
  • For a in depth answer https://stackoverflow.com/questions/72238175/react-18-useeffect-is-getting-called-two-times-on-mount. – Youssouf Oumar Sep 21 '22 at 15:59

1 Answers1

42

Thanks to Joel Hager I was able to get it working by editing by next.config.js to

const nextConfig = {
  reactStrictMode: false,
};

and restarting my app.

cormacncheese
  • 1,251
  • 1
  • 13
  • 27
  • 4
    I also got duplicated execution of useEffect and disabling it also worked for me, but I hate not knowing why. ReactStrictMode is supposed to help highlighting potential problems, not create them. Does anyone understand why is this happening? I am using next v12.1.6 + react v18.1.0 – Ander Jul 01 '22 at 04:55
  • 2
    You shouldn't forget to restart your server as well. `next.config.js` is applied on server startup. – Opemipo Bolaji Jul 09 '22 at 09:14
  • 1
    You shouldn't be systematically deactivating `StrictMode`. See https://stackoverflow.com/questions/72238175/react-18-useeffect-is-getting-called-two-times-on-mount – Youssouf Oumar Sep 21 '22 at 15:58
  • still happening with next v13, internet is saying this is a react issue so i'm not sure what is going on and the solution for it. disabling strict mode sounds wrong. – Pencilcheck Jan 24 '23 at 22:20
  • @Ander maybe you use rewrite https://stackoverflow.com/questions/72302343/next-js-app-is-rendered-twice-with-rewrites – fisch Mar 17 '23 at 09:37
  • 2 days of my life wasted on this issue. Thank you!! – Alin Faur Apr 21 '23 at 23:42
  • 1
    You saved my days. Thanks. – mazend Jul 25 '23 at 07:00