AI Hints
Home›React Tutorial›Testing and Shipping
React · Lesson 84 of 120

Server Components

The idea.

⏱ 2 min read▶ Video at 1:11:40🎓 Free
Watch this lesson in the React courseWatch on YouTube ↗Full React course

Everything so far runs in the browser. Server components run on the server instead. They can read a database directly, and send finished HTML, with none of their code shipped to the browser.

  • So far: browser
  • Server components
  • No code shipped

A server component

This component is async, and runs only on the server. It reads products straight from the database, with no effect, and no loading state. Its code never reaches the browser. Only the add button, a client component, does.

ProductsPage.jsxjsx
import { db } from "./db";
import AddButton from "./AddButton"; // "use client" inside

export default async function ProductsPage() {
  const products = await db.products.findAll();
  return (
    <ul>
      {products.map(p => (
        <li key={p.id}>{p.name} — £{p.price} <AddButton id={p.id} /></li>
      ))}
    </ul>
  );
}

Server or client

Server components fetch data, and keep secrets safe, but can't use state or effects. Client components, marked with use client, handle clicks, state, and the browser.

Server

  • Data and secretsNo state or effectsNo JS shipped

Client

  • "use client"State and eventsRuns in the browser

Summary

Server components run on the server, and need a framework to use. Next, frameworks.

Key takeaways
  • async components
  • "use client"
  • Less JavaScript
Next up: Frameworks — Next.js and others