Common Mistakes with Server and Client Components
メニューを表示するにはスワイプしてください
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.
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.
フィードバックありがとうございます!
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください