Server Components (Default)
- Execution Environment: Runs on the server
- Advantages:
- Not sent to the browser, reducing JS bundle size and improving performance.
- Can fetch data directly from databases or APIs inside the component (no need for
useEffect
).
- Pre-rendered on the server, making it better for SEO.
- Best Use Cases:
- Components that only display data and don’t require user interaction (e.g., blog posts, product listings, SEO-related pages).
- Fetching data directly from a database without exposing API calls to the client.
- Optimizing frontend performance by reducing JavaScript execution on the client.
export default async function ProductList() {
const res = await fetch("<https://fakestoreapi.com/products>", { cache: "no-store" });
const products = await res.json();
return (
<ul>
{products.map((product) => (
<li key={product.id}>{product.title}</li>
))}
</ul>
);
}
cache: "no-store"
ensures fresh data on every request (use "force-cache"
for static data).
- No JavaScript is sent to the client, reducing bundle size.
Client Components (use client
required)
- Execution Environment: Runs in the browser
Required When:
- Using state, side effects, or refs (
useState
, useEffect
, useRef
).
- Handling event listeners (
onClick
, onChange
).
- Rendering interactive elements (modals, tabs, buttons).
"use client";
import { useState } from "react";
export default function Counter() {
const [count, setCount] = useState(0);
return <button onClick={() => setCount((prev) => prev + 1)}>Count: {count}</button>;
}
- Marked as a Client Component with
"use client"
.
- Uses
useState
, requiring it to run in the browser.