What are Server Components?
- React course
- Expert
- Lesson 5/32
- 4 min
Learn that server components render on the server.
What are Server Components?
Server Components are components rendered on the server that send only HTML to the client. They can access databases and APIs directly; they do not enter the JavaScript bundle.
To render a component on the client you write 'use client' at the top of the file. This declares it as an interactive browser component.
In the Next.js App Router all components are server components by default.
The 'use client' directive
To turn a file into a client component you write 'use client' at the top. All components in that file render in the browser; you can use useState and onClick.
Data flows from server components to client components as props; but functions cannot be passed. A client component can be a child of a server component.
A component cannot be both server and client; the directive works per file.
Practice Write the ProductList server component
Write a ProductList server component. Make it an async function. Fetch data with await fetch('https://api.example.com/products') and parse with res.json(). Inside a <ul> map products to <li key={p.id}>{p.name}</li>. Export it.
Starter code
// Write the ProductList server component hereSample solution
async function ProductList() {
const res = await fetch('https://api.example.com/products');
const products = await res.json();
return (
<ul>{products.map(p => <li key={p.id}>{p.name}</li>)}</ul>
);
}
export default ProductList;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the default component type in App Router?
- Client Component
- Server Component Correct answer
- Shared Component
- Edge Component
Explanation: Server Component is the default in App Router.
2 Fill in the blank: mark a client component
'____';
import { useState } from 'react';
function LikeButton() {
const [n, setN] = useState(0);
return <button onClick={() => setN(n + 1)}>{n}</button>;
}
'use client';
import { useState } from 'react';
function LikeButton() {
const [n, setN] = useState(0);
return <button onClick={() => setN(n + 1)}>{n}</button>;
}
Explanation: 'use client' starts a client component.
3 Match component types
| Term | Meaning |
|---|---|
Server Component |
Rendered on server |
Client Component |
Rendered in browser |
'use client' |
Marks client |
async |
Allows data fetching |