21

In Next-JS, UseEffect() is run twice. I heard that you need to put an empty array as the second argument to fix this in React. In my case, in Next-JS, this does not work. (As far as I know, Next-JS is based on React).

I found one way: in next.config.js set reactStrictMode: false. And it works, the UserEffect is called once.

But this method does not suit me, because. I need to use React's strict mode.

_app.js:

import '../styles/globals.css';
import React, { useEffect, useState, useRef } from 'react';

function MyApp({ Component, pageProps }) {
  if (typeof window !== "undefined") {
    useEffect(() => {

      console.log('Component Did Mount') //called twice :c

    }, [])


  return <Component {...pageProps} />
}


export default MyApp
5
  • 5
    Are you using react 18? If so, it is expected behavior in strict mode that the component mounts twice, which means the effect will run twice. Commented Apr 21, 2022 at 16:36
  • 1
    btw, you can remove the condition. useEffect only runs client-side, so window is guaranteed to be defined. docs Commented Apr 21, 2022 at 16:45
  • 2
    From the react docs: Don’t call Hooks inside loops, conditions, or nested functions. reactjs.org/docs/hooks-rules.html Commented Apr 21, 2022 at 16:57
  • For a in depth answer stackoverflow.com/questions/72238175/…. Commented Sep 21, 2022 at 15:54
  • 1
    I believe this question should not be closed as a duplicate due to the fact that this is specifically for nextjs instead of vanilla react. I actually encountered this problem before in vanilla react and fixed it after seeing the questions this is marked as a duplicate of, but now that I started using nextjs, I had to refer specifically to this one for my solution because the answer in both is slightly different, although, I'll admit, very obvious. Commented Oct 8, 2023 at 8:08

1 Answer 1

38

React.StrictMode is used to help during development, so why are you concerned about the double execution ? By the way the rules of hooks say that you cannot place an hook inside a loop or an if statement.

Here are the code examples to address both issues:

  1. NextJS to config React's Strict Mode edit next.config.js file
module.exports = {
    reactStrictMode: false,
}
  1. Move your if statement inside the useEffect hook
import { useEffect } from 'react';

function MyApp({ Component, pageProps }) {
    useEffect(() => {
    if (typeof window !== "undefined") {
        console.log('Component Did Mount') // called once
    }, [])

    return <Component {...pageProps} />
}

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

1 Comment

For a more detailed answer: stackoverflow.com/questions/72238175/….

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.