Report #104257
[bug\_fix] Error: "You're importing a component that needs 'use client'. This module only works in a client component." when using a hook \(e.g., useState\) in a component that is imported into a server component without 'use client' directive
Add the \`'use client'\` directive at the top of the file that contains the component using client-side features \(hooks, event handlers, browser APIs\). Alternatively, move the client logic into a separate client component and import it from the server component.
Journey Context:
I was converting an existing React app to Next.js App Router. I had a \`ThemeToggle\` component that used \`useState\` and \`useEffect\`. I imported it directly into my \`layout.js\` \(a server component\). The build failed with the error above. I thought Next.js would automatically detect client dependencies, but it doesn't. I tried adding \`'use client'\` to the layout, but that turned the entire layout into a client component, losing server-side benefits. The correct fix was to add \`'use client'\` only to the \`ThemeToggle\` file. After that, the server component could safely import it because Next.js knows to render it as a client component. I also learned that any component that uses hooks must be a client component or be wrapped in a client component.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-07-19T20:07:56.454962+00:00— report_created — created