Provides guidance on React Server Components vs Client Components decision-making in Bellog. Triggers when creating new components.
This skill defines when to use Server Components vs Client Components in the Bellog blog project.
Default to Server Components. Only use Client Components when necessary.
Does the component need interactivity or browser APIs?
ā
āā NO (static rendering)
ā āā ā
Server Component
ā - Fast initial load
ā - Zero client JavaScript
ā - Can use async/await directly
ā - Can access server-only APIs
ā - Better SEO
ā
āā YES (hooks, events, browser APIs)
āā š“ Client Component ("use client")
- Can use hooks (useState, useEffect, etc.)
- Can attach event handlers
- Can access browser APIs
- Can use framer-motion
- Can use next-themes
ā Use Server Components when:
// ā
Server Component (no "use client")
import { getAllPosts } from '@/lib/posts';
export default async function PostList() {
// Can use async/await directly
const posts = await getAllPosts();
return (
<div>
{posts.map(post => (
<PostCard key={post.id} post={post} />
))}
</div>
);
}
Server Components:
app/page.tsx - Home page (fetches recent posts)app/posts/page.tsx - Posts list (fetches all posts)app/posts/[slug]/page.tsx - Post detail (fetches single post)PostList component - Renders static post gridPostCard component - Static card renderingš“ Use Client Components when you need:
1. React Hooks:
useState, useEffect, useContextuseRef, useCallback, useMemouseScrollSpy, etc.)2. Event Handlers:
onClick, onChange, onSubmitonScroll, onMouseEnter, onMouseLeave3. Browser APIs:
window, document, localStorageIntersectionObserver, ResizeObservernavigator, location4. Third-Party Libraries:
"use client"; // Required at top of file
import { useState } from 'react';
import { motion } from 'framer-motion';
export function InteractiveCard() {
const [isHovered, setIsHovered] = useState(false);
return (
<motion.div
onMouseEnter={() => setIsHovered(true)}
onMouseLeave={() => setIsHovered(false)}
whileHover={{ scale: 1.02 }}
>
{/* Interactive content */}
</motion.div>
);
}
Client Components:
Navbar.tsx - Scroll detection, theme toggleIntro.tsx - TypeAnimation, framer-motionNotionToc.tsx - Scroll spy, active section trackingtemplate.tsx - Page transition animationsThemeToggle.tsx - next-themes integrationProgressBar.tsx - Scroll progress trackingGiscusComments.tsx - Comment system (requires client JS)Best Practice: Keep most as Server, wrap interactive parts as Client.
// app/posts/[slug]/page.tsx (Server Component)
import { getPostBySlug } from '@/lib/posts';
import { NotionToc } from '@/components/posts/NotionToc'; // Client
import { PostNavigation } from '@/components/posts/PostNavigation'; // Client
import { PostRenderer } from '@/components/posts/PostRenderer'; // Server
export default async function PostPage({ params }) {
const post = await getPostBySlug(params.slug);
return (
<div>
<NotionToc headings={post.headings} /> {/* Client island */}
<PostRenderer content={post.content} /> {/* Server */}
<PostNavigation prev={post.prev} next={post.next} /> {/* Client */}
</div>
);
}
// Server Component
async function ParentServer() {
const data = await fetchData(); // Server-side fetch
return <ChildClient data={data} />; // Pass as props
}
// Client Component
"use client";
function ChildClient({ data }) {
const [selected, setSelected] = useState(data[0]);
// Use data in client component
}
Important: Don't pass functions or Date objects - serialize data!
// ā Wrong
<ClientComponent date={new Date()} />
// ā
Correct
<ClientComponent date={new Date().toISOString()} />
Wrap Client Component to Reduce Bundle:
// Layout (Server Component)
import { ClientHeader } from './ClientHeader';
export function Layout({ children }) {
return (
<>
<ClientHeader /> {/* Only this is client */}
<main>{children}</main> {/* Can be server */}
</>
);
}
import { cache } from 'react';
// Deduplicates requests within a single render
export const getPost = cache(async (id: string) => {
return await fetchPost(id);
});
import { cache } from 'react';
import { unstable_cache } from 'next/cache';
export const getAllPosts = cache(
unstable_cache(
async () => {
return await getAllPostsFromNotion();
},
['all-posts'], // Cache key
{
revalidate: 3600, // 1 hour
tags: ['posts', 'notion']
}
)
);
Example from /src/lib/posts.ts:
export const getAllPosts = cache(
unstable_cache(
async () => {
const posts = await getAllPostsFromNotion();
return posts.sort((a, b) =>
new Date(b.date).getTime() - new Date(a.date).getTime()
);
},
["all-posts"],
{
revalidate: 3600, // Revalidate every hour
tags: ["posts", "notion"]
}
)
);
// app/api/revalidate/route.ts
import { revalidateTag } from 'next/cache';
export async function POST(request: Request) {
const secret = request.nextUrl.searchParams.get('secret');
if (secret !== process.env.REVALIDATION_SECRET) {
return Response.json({ message: 'Invalid' }, { status: 401 });
}
revalidateTag('notion'); // Invalidate all Notion caches
return Response.json({ revalidated: true });
}
// ā Wrong (doesn't need "use client")
"use client";
export function StaticCard({ title, description }) {
return (
<div>
<h3>{title}</h3>
<p>{description}</p>
</div>
);
}
// ā
Correct (Server Component)
export function StaticCard({ title, description }) {
return (
<div>
<h3>{title}</h3>
<p>{description}</p>
</div>
);
}
// ā Wrong (needs "use client" because of useState)
import { useState } from 'react';
export function Counter() {
const [count, setCount] = useState(0); // Error!
return <button onClick={() => setCount(count + 1)}>{count}</button>;
}
// ā
Correct
"use client";
import { useState } from 'react';
export function Counter() {
const [count, setCount] = useState(0);
return <button onClick={() => setCount(count + 1)}>{count}</button>;
}
// ā Wrong (Client Components can't be async)
"use client";
export default async function Page() {
const data = await fetchData(); // Error!
return <div>{data}</div>;
}
// ā
Correct (Server Component)
export default async function Page() {
const data = await fetchData();
return <ClientChild data={data} />;
}
// ā Wrong (functions can't be serialized)
async function ServerComponent() {
const handler = () => console.log('click');
return <ClientComponent onClick={handler} />; // Error!
}
// ā
Correct (define handler in client component)
"use client";
function ClientComponent() {
const handler = () => console.log('click');
return <button onClick={handler}>Click</button>;
}
When creating a component, ask:
If any checkbox is true, use "use client". Otherwise, keep as Server Component.
Bundle Size: 0 KB (no client JavaScript) Initial Load: Fast (pre-rendered HTML) Hydration: None needed SEO: Excellent (fully rendered)
Bundle Size: Adds JavaScript to bundle Initial Load: Slower (needs hydration) Hydration: Required SEO: Good (but requires hydration)
Example:
Navbar.tsx (Client): ~5 KBIntro.tsx with framer-motion (Client): ~30 KBPostList (Server): 0 KB// Always start here
export function Component() {
// ...
}
// Only add "use client" when needed
// ā
Good - Only button is client
function Page() {
return (
<div>
<StaticContent /> {/* Server */}
<InteractiveButton /> {/* Client */}
</div>
);
}
// ā Bad - Everything is client
"use client";
function Page() {
return (
<div>
<StaticContent /> {/* Unnecessary client */}
<InteractiveButton />
</div>
);
}
// ā
Extract interactive part
function ServerCard({ data }) {
return (
<div>
<StaticHeader data={data} /> {/* Server */}
<InteractiveActions id={data.id} /> {/* Client */}
</div>
);
}
"use client";
function InteractiveActions({ id }) {
const [liked, setLiked] = useState(false);
return <button onClick={() => setLiked(!liked)}>Like</button>;
}
// Layout stays Server
function Layout({ children }) {
return (
<>
<Header /> {/* Client component */}
<main>{children}</main> {/* Can be Server */}
<Footer /> {/* Server component */}
</>
);
}
// Server Component (default)
export async function Component() {
const data = await fetchData();
return <div>{data}</div>;
}
// Client Component (when needed)
"use client";
import { useState } from 'react';
export function Component() {
const [state, setState] = useState();
return <button onClick={() => setState(...)}>Click</button>;
}
// Client with framer-motion
"use client";
import { motion } from 'framer-motion';
export function Component() {
return <motion.div animate={{ opacity: 1 }}>...</motion.div>;
}
// Pass data Server ā Client
function Server() {
const data = await fetch();
return <Client data={data} />; // Serialize data
}
Remember: Every "use client" adds to bundle size. Be intentional about where you place client boundaries.