'In Next-JS, UseEffect() is run twice. I put an empty array as the second argument, it did not help. How to fix it? [duplicate]

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


Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Cesare Polonara