CodeBlanks Logo Icon CodeBlanks

Server Components

Learn what server components are and how they differ.

Server Components

Server Components (RSC) render on the server and ship no JavaScript to the browser. They can directly access databases, the file system and private APIs.

RSC cannot use useState, useEffect or browser APIs. If you need interactivity, that piece becomes a Client Component.

This split keeps the JavaScript bundle small and speeds up the first load.

use client directive

If you put "use client" at the top of a file, all components in that file become Client Components. They can use useState, useEffect and event handlers.

A Server Component can import Client Components; the reverse is not allowed. This boundary optimizes performance.

Splitting interactive pieces into small Client Components is best practice.

Practice Client Counter

Write a Counter component with "use client" at the top. Keep n in useState(0), render <button onClick={() => setN(n + 1)}>{n}</button>. export default Counter.

Starter code

App.jsx
// app/counter.js

// Üste use client direktifini ekle, sonra Counter bileşenini yaz

Sample solution

App.jsx
// app/counter.js
"use client";
import { useState } from "react";

export default function Counter() {
  const [n, setN] = useState(0);
  return <button onClick={() => setN(n + 1)}>{n}</button>;
}

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which hook is NOT allowed in RSC?

  • console.log
  • fetch
  • useState Correct answer
  • async/await

Explanation: useState is not allowed in RSC; RSC is not interactive.

2 use client directive

Question
"____"

import { useState } from "react";

export default function Counter() {
  const [n, setN] = useState(0);
  return <button onClick={() => setN(n + 1)}>{n}</button>;
}
Answer
"use client"

import { useState } from "react";

export default function Counter() {
  const [n, setN] = useState(0);
  return <button onClick={() => setN(n + 1)}>{n}</button>;
}

Explanation: "use client" makes the file a Client Component.

3 Server Components: match the terms

Term Meaning
Server Component Server render
Client Component Interactive
"use client" Directive
useState Client only

All lessons in Advanced