I have a very simple NextJS app in v13.4+ and it is running useEffect 3 times (even though it is set with an empty dependency array.)
I was hoping that it would only run 1 time (on the equivalent of componentDidMount) due to the empty array.
I'm not sure why useEffect is running three times. I put a getData call in the useEffect and I prefer this not to run three times when the user goes to the page.
// /app/page.js
'use client';
import react, { useEffect, useState } from 'react'
export default Page() {
const [myData, setMyData] = useState([]);
// this is calling a router handler
const getData = async () => {
const response = await fetch('/api/data', {
method: 'GET',
});
if (response.ok) {
console.log('Response.Ok');
const { data } = await response.json();
setMyData((prev) => data);
} else {
console.log('Error');
}
};
useEffect(() => {
getData();
}, [])
return (<div>{myData.map((item, index)=>(<div key={index}>convertToUpperCase(item.name)</div>)}</div>)
}
If you are running your app locally (from Terminal/localhost), upon changes in code, NextJS will push changes to your running instances of the app (regardless of whether you are actively looking at the tab). This is likely the source of the issue.
React Strict mode is turned off by default in NextJS v13.4.7 app router
. With some experimenting of how many times the useEffect runs, I can confirm that strict mode is off by default.
Going to the file next.config.js
at the root of the project, you will see the following (where you can turn it on or off).
// STRICT MODE IS OFF BY DEFAULT
/** @type {import('next').NextConfig} */
const nextConfig = {
};
module.exports = nextConfig;
// STRICT MODE ON - THIS DOES INCREASE TIMES USE EFFECT IS RUN BY 1
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
};
module.exports = nextConfig;
// STRICT MODE EXPLICITLY OFF - THIS MATCHES THE DEFAULT CASE
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: off,
};
module.exports = nextConfig;
H/T to the comments and answers who referenced React Strict mode.