React Advanced

Server Components

RSC architecture, server vs client components, streaming, and data fetching.

Advertisement

Server Components

RSC architecture, server vs client components, streaming, and data fetching.

Overview

React Server Components run on the server, reducing client bundle size and enabling direct data access.

Key Concepts

  • Server Components — Default in Next.js App Router, run on server only
  • Client Components — Marked with 'use client', run on client
  • Streaming — Progressive rendering with Suspense boundaries
  • Server Actions — Functions that run on the server, called from client
  • Bundle Size — Server components don't add to client JavaScript

Code Examples

// Server Component (default)
async function ProductList() {
  const products = await db.products.findMany();
  return (
    <ul>
      {products.map(product => (
        <li key={product.id}>
          <h3>{product.name}</h3>
          <p>${product.price}</p>
          <AddToCartButton productId={product.id} />
        </li>
      ))}
    </ul>
  );
}

// Client Component
'use client';
function AddToCartButton({ productId }) {
  const [adding, setAdding] = useState(false);
  
  async function handleAdd() {
    setAdding(true);
    await addToCart(productId);
    setAdding(false);
  }

  return (
    <button onClick={handleAdd} disabled={adding}>
      {adding ? 'Adding...' : 'Add to Cart'}
    </button>
  );
}

// Server Action
'use server';
async function addToCart(productId) {
  await db.carts.update({
    where: { userId: currentUser.id },
    data: { items: { push: productId } }
  });
}

Practice

Build a product page with server-rendered product data and client-side cart functionality.