Server Components: can I use useState or onClick in them?

posée a month ago490 vuesen

5

I added an onClick to a button in app/page.tsx and got: Event handlers cannot be passed to Client Component props. Do I need to make the whole page a client component?

Diagnostic IA

Généré par IA. Ce n'est pas une réponse — la communauté ci-dessous le confirme ou le corrige. Vérifiez toujours avant de vous y fier.

posée a month ago

2 réponses

8
✓
✓ Réponse acceptée

No. Keep the page as a Server Component and extract only the interactive part into a small Client Component:

// app/LikeButton.tsx
'use client';
import { useState } from 'react';

export function LikeButton() {
  const [likes, setLikes] = useState(0);
  return <button onClick={() => setLikes(likes + 1)}>👍 {likes}</button>;
}
// app/page.tsx (Server Component, can fetch data directly)
import { LikeButton } from './LikeButton';

export default async function Page() {
  const post = await getPost();
  return <article><h1>{post.title}</h1><LikeButton /></article>;
}

Server Components can't use state, effects, or event handlers. Push 'use client' as far down the tree as possible so most of your UI stays server-rendered and ships no JS.

Connectez-vous pour dire si ça a marché.

answered a month ago
5

You can also pass Server Components *as children* into a Client Component (e.g. a client-side <Tabs> wrapping server-rendered panels). The children stay server-rendered even though the wrapper is interactive.

Connectez-vous pour dire si ça a marché.

answered a month ago

Sign in and verify your email to post an answer.