Skip to content

Client Component vs Server Component

Client Components

คอมโพเนนต์ที่รันบนฝั่งไคลเอนต์ (ในเบราว์เซอร์)

tsx
"use client"; // ต้องระบุสำหรับ Client Components

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

Server Components

คอมโพเนนต์ที่รันบนเซิร์ฟเวอร์ (ค่าเริ่มต้นใน Next.js 13+)

tsx
// ไม่ต้องระบุ 'use client'
export default function ServerComponent() {
  // สามารถเรียกใช้ API โดยตรงได้
  const data = await fetchData();
  return <div>{data}</div>;
}

Component Patterns

Basic Component

คอมโพเนนต์พื้นฐานใน React

tsx
function Greeting() {
  return <h1>Hello, World!</h1>;
}

Component with Props

คอมโพเนนต์ที่รับค่าผ่าน props

tsx
interface GreetingProps {
  name: string;
}

function Greeting({ name }: GreetingProps) {
  return <h1>Hello, {name}!</h1>;
}

Component Composition

เทคนิคการประกอบคอมโพเนนต์เข้าด้วยกัน

tsx
function Card({ children }: { children: React.ReactNode }) {
  return <div className="card">{children}</div>;
}

function App() {
  return (
    <Card>
      <Greeting name="John" />
    </Card>
  );
}