🌐 Web Development

React Server Components

RSC

React components rendered on the server. Reduces bundle size and allows direct DB access.

πŸ“– Detailed Explanation

React Server Components (RSC) is a new component paradigm developed by the React team, in which components run only on the server and only the rendering result is sent to the client. Unlike conventional SSR (Server-Side Rendering), RSC is not included in the JavaScript bundle, so the bundle size is dramatically reduced. If heavy libraries (moment.js, lodash, etc.) are used only in Server Components, they are not sent to the client.

A key feature of RSC is that async/await can be used directly in components. Server Components can directly access databases, file systems, and internal APIs, and fetch data without useEffect or React Query. This solves the Waterfall request problem and makes it possible to take advantage of the low latency between the server and the database.

Server Components and Client Components are clearly distinguished. Client Components must have the 'use client' directive added at the top of the file, and are used when useState, useEffect, event handlers, or browser APIs are needed. Server Components are the default, and they can include Client Components as children, but the reverse is not possible (passing them as props is possible).

The Next.js 13+ App Router is the representative implementation of RSC. page.tsx, layout.tsx, loading.tsx, and error.tsx work as Server Components by default, and combined with Streaming SSR, they enable progressive rendering. React 19 also introduced Server Actions, so form submissions and mutations can be handled directly on the server.

πŸ’» Code Example

Server Component (Next.js App Router)
// app/posts/page.tsx - μ„œλ²„ μ»΄ν¬λ„ŒνŠΈ (κΈ°λ³Έκ°’)
// 'use client' μ—†μœΌλ©΄ μ„œλ²„ μ»΄ν¬λ„ŒνŠΈ
import { prisma } from '@/lib/prisma';
import { formatDate } from 'date-fns'; // 이 λΌμ΄λΈŒλŸ¬λ¦¬λŠ” λ²ˆλ“€μ— 포함 μ•ˆ 됨!

// async μ»΄ν¬λ„ŒνŠΈ - μ„œλ²„μ—μ„œλ§Œ κ°€λŠ₯
export default async function PostsPage() {
    // DB 직접 μ ‘κ·Ό (API λΆˆν•„μš”)
    const posts = await prisma.post.findMany({
        include: { author: true },
        orderBy: { createdAt: 'desc' },
        take: 10,
    });

    // 무거운 데이터 μ²˜λ¦¬λ„ μ„œλ²„μ—μ„œ
    const processedPosts = posts.map(post => ({
        ...post,
        excerpt: post.content.slice(0, 150),
        formattedDate: formatDate(post.createdAt, 'yyyyλ…„ Mμ›” d일'),
    }));

    return (
        <main className="container mx-auto py-8">
            <h1 className="text-3xl font-bold mb-6">μ΅œμ‹  κ²Œμ‹œκΈ€</h1>

            <div className="grid gap-4">
                {processedPosts.map(post => (
                    <article key={post.id} className="p-6 border rounded-lg">
                        <h2 className="text-xl font-semibold">{post.title}</h2>
                        <p className="text-gray-600 mt-2">{post.excerpt}...</p>
                        <div className="mt-4 text-sm text-gray-500">
                            <span>{post.author.name}</span>
                            <span className="mx-2">β€’</span>
                            <span>{post.formattedDate}</span>
                        </div>
                    </article>
                ))}
            </div>
        </main>
    );
}

// 메타데이터도 μ„œλ²„μ—μ„œ 생성
export async function generateMetadata() {
    const totalPosts = await prisma.post.count();

    return {
        title: `κ²Œμ‹œκΈ€ λͺ©λ‘ (${totalPosts}개)`,
        description: 'μ΅œμ‹  κ²Œμ‹œκΈ€μ„ ν™•μΈν•˜μ„Έμš”',
    };
}
Client Component + Server Actions
// app/posts/actions.ts - Server Actions
'use server';

import { prisma } from '@/lib/prisma';
import { revalidatePath } from 'next/cache';

export async function createPost(formData: FormData) {
    const title = formData.get('title') as string;
    const content = formData.get('content') as string;

    await prisma.post.create({
        data: { title, content, authorId: 1 }
    });

    // μΊμ‹œ λ¬΄νš¨ν™” - λͺ©λ‘ νŽ˜μ΄μ§€ κ°±μ‹ 
    revalidatePath('/posts');
}

export async function deletePost(id: number) {
    await prisma.post.delete({ where: { id } });
    revalidatePath('/posts');
}

// -------------------------------------------------

// components/CreatePostForm.tsx - ν΄λΌμ΄μ–ΈνŠΈ μ»΄ν¬λ„ŒνŠΈ
'use client';

import { useFormStatus } from 'react-dom';
import { createPost } from '@/app/posts/actions';

function SubmitButton() {
    const { pending } = useFormStatus();

    return (
        <button
            type="submit"
            disabled={pending}
            className="bg-blue-500 text-white px-4 py-2 rounded disabled:opacity-50"
        >
            {pending ? 'μ €μž₯ 쀑...' : 'κ²Œμ‹œκΈ€ μž‘μ„±'}
        </button>
    );
}

export function CreatePostForm() {
    return (
        <form action={createPost} className="space-y-4">
            <input
                name="title"
                placeholder="제λͺ©"
                required
                className="w-full border p-2 rounded"
            />
            <textarea
                name="content"
                placeholder="λ‚΄μš©"
                required
                rows={5}
                className="w-full border p-2 rounded"
            />
            <SubmitButton />
        </form>
    );
}

// -------------------------------------------------

// app/posts/new/page.tsx - μ„œλ²„ μ»΄ν¬λ„ŒνŠΈμ—μ„œ ν΄λΌμ΄μ–ΈνŠΈ μ»΄ν¬λ„ŒνŠΈ μ‚¬μš©
import { CreatePostForm } from '@/components/CreatePostForm';

export default function NewPostPage() {
    return (
        <main className="max-w-2xl mx-auto py-8">
            <h1 className="text-2xl font-bold mb-6">μƒˆ κ²Œμ‹œκΈ€ μž‘μ„±</h1>
            {/* ν΄λΌμ΄μ–ΈνŠΈ μ»΄ν¬λ„ŒνŠΈ μ‚½μž… */}
            <CreatePostForm />
        </main>
    );
}

πŸ—£οΈ Examples of Practical Conversations

πŸ’Ό Architecture Discussion
"What improves if we switch from the existing React + API structure to the Next.js App Router?"

"The boilerplate of creating API endpoints and fetching goes away. Since you query the DB directly in Server Components, the N+1 problem is easy to solve too, and you can use an ORM like Prisma right in your frontend code. The bundle size can also shrink by 30-50%."
πŸ” Code Review
"I'm trying to use useState in this component, but I get an error saying 'use client' is missing."

"You can't use Hooks in Server Components. Split only the parts that need state into small Client Components. For example, if the list is rendered on the server and only the like button is a client component, you can minimize the bundle size while still allowing interaction."
πŸ“± Technical interview
"What is the difference between SSR and React Server Components?"

"SSR generates HTML on the server, but it also sends the component JavaScript to the client for Hydration. RSC doesn't send the Server Component's JavaScript at all. Only the rendering result (React Tree) is sent to the client, so the bundle size is dramatically reduced."

Take a mock interview on this topic β†’ WIA SOOM AI Interview Β· Start for free

⚠️ Cautions

  • Only serializable props - Props passed from a Server Component to a Client Component must be JSON-serializable. Functions, Date objects, Map/Set, and the like cannot be passed.
  • Understand the 'use client' boundary - Everything that a Client Component imports is also included in the client bundle. Split Client Components into the smallest scope necessary.
  • Caching strategy is essential - If a Server Component queries the DB on every request, performance drops. Cache appropriately with revalidate, cache, unstable_cache, and the like.

πŸ”— Related Terms

πŸ“š Learn More