Skip to main content
Advertisement

Next.js: Server Components and Rendering (Step 3)

1. Server Components

A core concept introduced since Next.js 13, where by default, all components are Server Components.

  • They render only on the server, significantly reducing the JavaScript bundle size sent to the client.
  • They have direct access to the database or file system.
  • They can fetch data securely without exposing sensitive API keys to the browser.

2. Client Components

Used when browser interactivity (such as useState, useEffect, onClick, etc.) is required. You must add the 'use client'; directive at the very top of the file.

'use client';

import { useState } from 'react';

export default function InteractiveCounter() {
const [count, setCount] = useState(0);
return <button onClick={() => setCount(count + 1)}>{count}</button>;
}

3. Data Fetching

In Server Components, you can fetch data directly using async/await.

// app/posts/page.tsx
async function getPosts() {
const res = await fetch('https://api.example.com/posts');
return res.json();
}

export default async function Page() {
const posts = await getPosts();
return (
<ul>
{posts.map(post => <li key={post.id}>{post.title}</li>)}
</ul>
);
}

4. Overview of Rendering Strategies

  • SSG (Static Site Generation): Generates pages at build time. (Default)
  • SSR (Server-Side Rendering): Generates pages on the server for each request.
  • ISR (Incremental Static Regeneration): Generates pages statically but updates them in the background at specific intervals.
Advertisement