Why useEffect runs multiple times in Next.js
Answered
West African Crocodile posted this in #help-forum
West African CrocodileOP
I'm developing a Time Tracking component in Next.js application. Here's my TimeTracking (./app/components/TimeTracking.tsx) component:
'use client';
import React, { useEffect, useState } from 'react';
import { useSession } from 'next-auth/react';
const TimeTracking = () => {
const { data: session } = useSession();
useEffect(() => {
console.log('session ===> ', session);
let initialTimeStampSetUp: boolean = false;
console.log('initialTimeStampSetUp ===> ', initialTimeStampSetUp);
if (!initialTimeStampSetUp) {
const initialTimeStamp: Date = new Date();
console.log('initialTimeStamp ===> ', initialTimeStamp);
initialTimeStampSetUp = true;
console.log('initialTimeStampSetUp ===> ', initialTimeStampSetUp);
}
if (typeof window !== 'undefined' && session) {
const handleBeforeUnload = () => {
const requestBody = JSON.stringify({
initialTimeStamp: initialTimeStamp,
date: new Date(),
});
navigator.sendBeacon(`/api/user/${session?.user?._id}`, requestBody);
};
window.addEventListener('beforeunload', handleBeforeUnload);
return () => {
window.removeEventListener('beforeunload', handleBeforeUnload);
};
}
}, [session]);
return (
<>
<p>Time Tracking</p>
</>
);
};
export default TimeTracking;Answered by not-milo.tsx
That's expected. Every time your component re-renders the useEffect hook gets executed twice in dev mode if StrictMode is enabled.
StrictMode renders components twice (on dev but not production) in order to detect any problems with your code and warn you about them (which can be quite useful).
11 Replies
That's expected. Every time your component re-renders the useEffect hook gets executed twice in dev mode if StrictMode is enabled.
StrictMode renders components twice (on dev but not production) in order to detect any problems with your code and warn you about them (which can be quite useful).
Answer
West African CrocodileOP
@not-milo.tsx but it keeps re-rendering over and over. more than 2 times
That's an issue in your code. There's something that causes the component to be re-rendered multiple times...
It could also be that the session keeps updating which results in your effect being run again on each update
West African CrocodileOP
could be
thank you
do you have any suggestions on how to debug it?
Nothing that could help you given only the code of your component. Double check how you're using it throughout your application. There might be something else further up the tree that's triggering the re-renders.
Also, there's a setting in the Chrome dev tools called "Paint Flashing" that highlights what pieces of the page need to be repainted after a re-render. That's usually a good indicator of what's changing in your app without needing to place a bunch of console logs everywhere.
West African CrocodileOP
thanks a lot
No problem ✌ðŸ»