Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Impara Common Mistakes with Server and Client Components | Section
/
Building Web Apps with Next.js

bookCommon Mistakes with Server and Client Components

Scorri per mostrare il menu

Working with Server and Client Components is a powerful feature of Next.js, but it can also lead to confusion if used incorrectly.

Most mistakes happen when developers forget where code is running or use the wrong type of component for a task.

Understanding these common issues will help you avoid bugs and build cleaner applications.

Mistake 1 - Using Hooks in Server Components

Server Components do not run in the browser, so they cannot use React hooks like useState or useEffect.

export default function Page() {
  const [count, setCount] = useState(0); // ❌ Not allowed
  return <div>{count}</div>;
}

If you need state or effects, the component must be a Client Component.

Mistake 2 - Forgetting "use client"

If you create an interactive component but forget "use client", it will not work as expected.

import { useState } from "react";

export default function Counter() {
  const [count, setCount] = useState(0); // ❌ Error
  return <button>{count}</button>;
}

To fix this, add "use client" at the top of the file.

Mistake 3 - Using Browser APIs in Server Components

Server Components do not have access to browser APIs like window or localStorage.

export default function Page() {
  console.log(window.innerWidth); // ❌ Error
  return <div>Hello</div>;
}

This code must be moved to a Client Component.

Mistake 4 - Making Everything a Client Component

It may seem easier to add "use client" everywhere, but this reduces performance.

Client Components send more JavaScript to the browser, which can slow down your app.

Instead, keep components as Server Components unless interactivity is required.

Mistake 5 - Passing Non-Serializable Data

When passing data from Server to Client Components, the data must be serializable.

const data = {
  date: new Date(), // ❌ Problematic
};

Non-serializable values like functions or complex objects can cause errors.

Note
Note

How to Think Correctly

When building a component, ask:

  • Does this need interactivity? → use Client Component;
  • Does this only render data? → keep it as Server Component.

This simple rule helps you avoid most mistakes.

question mark

Which of the following is a common mistake when using Server Components?

Seleziona la risposta corretta

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 1. Capitolo 22

Chieda ad AI

expand

Chieda ad AI

ChatGPT

Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione

Sezione 1. Capitolo 22
some-alt