nextjs
component_error
ai_generated
true
Error: useState/useEffect can only be used in Client Components
ID: nextjs/server-component-client-hook
92%Fix Rate
90%Confidence
170Evidence
2023-01-01First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 14 | active | — | — | — |
Root Cause
React hooks used in a Server Component. Next.js App Router defaults to Server Components.
genericWorkarounds
-
95% success Add 'use client' directive at the top of the file that uses hooks
// Add as first line: 'use client';
-
90% success Extract the interactive part into a separate Client Component
// Split into Server + Client components: // app/page.tsx (Server Component): import InteractiveButton from './InteractiveButton'; export default function Page() { return <div><h1>Title</h1><InteractiveButton /></div>; } // app/InteractiveButton.tsx (Client Component): 'use client'; import { useState } from 'react'; export default function InteractiveButton() { const [count, setCount] = useState(0); return <button onClick={() => setCount(c => c + 1)}>{count}</button>; }Sources: https://nextjs.org/docs/app/building-your-application/rendering/composition-patterns
Dead Ends
Common approaches that don't work:
-
Make the entire page a Client Component
72% fail
Loses server-side rendering benefits for the whole page
-
Pass hooks through props from a parent Client Component
85% fail
Hooks cannot be passed as props, they must be called in the component
Error Chain
Preceded by:
Frequently confused with: