16

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)
  }, [])
5
  • 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. Commented Apr 12, 2022 at 0:17
  • @cSharp commented out getTransactions just including the console.log in useEffect and same thing, logged two hellos...strangest thing Commented Apr 12, 2022 at 0:18
  • 5
    Is your app using Strict Mode? Commented Apr 12, 2022 at 0:31
  • Even if it is in strict mode, useEffect with no dependency, will only run once unless your component remounts. Commented Apr 12, 2022 at 3:11
  • For a in depth answer stackoverflow.com/questions/72238175/…. Commented Sep 21, 2022 at 15:59

1 Answer 1

68

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.

Sign up to request clarification or add additional context in comments.

7 Comments

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
You shouldn't forget to restart your server as well. next.config.js is applied on server startup.
You shouldn't be systematically deactivating StrictMode. See stackoverflow.com/questions/72238175/…
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.
@Ander maybe you use rewrite stackoverflow.com/questions/72302343/…
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.