How to Fix useEffect Not Running in Next.js
useEffect may not run if the component is rendered on the server or if dependencies are missing or incorrect. Ensure useEffect is used inside a client component and that dependencies are properly set in the dependency array to trigger the effect.Why This Happens
Next.js does server-side rendering by default, so useEffect does not run on the server because it only runs in the browser after the component mounts. Also, if the dependency array is empty or missing dependencies, the effect may not run as expected.
import { useEffect } from 'react'; export default function MyComponent() { useEffect(() => { console.log('Effect ran'); }, []); return <div>Hello</div>; }
The Fix
Make sure your component is a client component by adding 'use client' at the top if using Next.js 13+ with the App Router. Also, specify dependencies correctly in the useEffect dependency array to control when it runs.
'use client'; import { useEffect, useState } from 'react'; export default function MyComponent() { const [count, setCount] = useState(0); useEffect(() => { console.log('Effect ran with count:', count); }, [count]); return <button onClick={() => setCount(count + 1)}>Increment</button>; }
Prevention
Always declare useEffect inside client components in Next.js. Use the 'use client' directive at the top of your file when using the App Router. Keep your dependency arrays accurate to avoid missing updates or infinite loops. Use ESLint with the React Hooks plugin to catch dependency issues early.
Related Errors
Other common issues include infinite loops caused by missing or incorrect dependencies, and effects not running due to conditional hook calls. Always call hooks unconditionally and check dependencies carefully.