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

poze a month ago487 gadeen

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?

Dyagnostik IA

Se IA ki fè l. Se pa yon repons — kominote a anba a konfime oswa korije l. Toujou verifye anvan ou fye l.

poze a month ago

2 Repons

8
✓
✓ Repons yo aksepte

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.

Konekte pou di lòt moun si li te mache.

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.

Konekte pou di lòt moun si li te mache.

answered a month ago

Sign in and verify your email to post an answer.