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
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:
next.config.js filemodule.exports = {
reactStrictMode: false,
}
useEffect hookimport { 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With