nextjs component_error ai_generated true

Error: useState/useEffect can only be used in Client Components

ID: nextjs/server-component-client-hook

Also available as: JSON · Markdown
92%Fix Rate
90%Confidence
170Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
14 active

Root Cause

React hooks used in a Server Component. Next.js App Router defaults to Server Components.

generic

Workarounds

  1. 95% success Add 'use client' directive at the top of the file that uses hooks
    // Add as first line:
    'use client';

    Sources: https://nextjs.org/docs/app/building-your-application/rendering/client-components#using-client-components-in-nextjs

  2. 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:

  1. Make the entire page a Client Component 72% fail

    Loses server-side rendering benefits for the whole page

  2. 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

Leads to:
Preceded by:
Frequently confused with: