S
S
soul72022-04-21 19:27:09
JavaScript
soul7, 2022-04-21 19:27:09

In Next-JS, the UseEffect() hook is run twice. I put an empty array as the second argument, it didn't help. How to fix it?

In Next-JS, the UseEffect() hook is run twice. I heard that you need to provide an empty array as the second argument to fix this in React.
In my case in Next-JS it doesn't 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, 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') //вызывается дважды :с
    }, [])


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


export default MyApp

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
wonderingpeanut, 2022-04-21
@wonderingpeanut

The strict mod renders each component twice. This only happens in development fashion, i.e. this will not happen in a production build.
There is no way to fix this except by disabling the strict mod.
You can add a condition to the user effect
if (notAlreadyExecuted) { ... } // do something

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question