Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 919
Alexei Avatar asked Nov 21 '25 08:11

Alexei


1 Answers

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
like image 175
Cesare Polonara Avatar answered Nov 22 '25 21:11

Cesare Polonara