0
0
NextjsDebug / FixBeginner · 4 min read

How to Fix useEffect Not Running in Next.js

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.

javascript
import { useEffect } from 'react';

export default function MyComponent() {
  useEffect(() => {
    console.log('Effect ran');
  }, []);

  return <div>Hello</div>;
}
Output
Effect ran (only in browser console, not during server render)
🔧

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.

javascript
'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>;
}
Output
Effect ran with count: 0 (on mount), then logs updated count on each button click
🛡️

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.

Key Takeaways

Add 'use client' directive to enable useEffect in Next.js App Router components.
useEffect only runs in the browser, not during server-side rendering.
Always specify correct dependencies in useEffect to control when it runs.
Use ESLint React Hooks rules to catch dependency mistakes early.
Never call hooks conditionally to avoid unexpected behavior.