Skip to content

บทที่ 6: React & Next.js

“ทำไมต้องสร้างห้องน้ำใหม่ทุกครั้ง ในเมื่อมีห้องน้ำสำเร็จรูปให้ประกอบ?”

The Blueprint (พิมพ์เขียว)

Section titled “The Blueprint (พิมพ์เขียว)”

เมื่อเว็บไซต์ซับซ้อนขึ้น การเขียน HTML/CSS/JS แบบดั้งเดิมจะเริ่มวุ่นวาย:

  • ปุ่มซ้ำกัน 50 ที่ แก้ทีต้องแก้ 50 จุด
  • State (สถานะ) กระจายไปทั่ว ตามไม่ถูก
  • โค้ดหลายพันบรรทัดในไฟล์เดียว

React = ระบบสร้างห้องสำเร็จรูป ทำครั้งเดียว ใช้ได้ทุกที่

The Construction Site (หน้างานก่อสร้าง)

Section titled “The Construction Site (หน้างานก่อสร้าง)”

🧱 Components — ห้องสำเร็จรูป

Section titled “🧱 Components — ห้องสำเร็จรูป”
// Button Component (ปุ่มสำเร็จรูป)
function Button({ children, onClick }) {
return (
<button
className="bg-blue-500 text-white px-4 py-2 rounded"
onClick={onClick}
>
{children}
</button>
);
}
// ใช้งาน
<Button onClick={handleClick}>กดที่นี่</Button>
<Button onClick={handleSubmit}>ส่งข้อมูล</Button>
<Button onClick={handleCancel}>ยกเลิก</Button>

🏠 การประกอบบ้านจาก Components

Section titled “🏠 การประกอบบ้านจาก Components”
function HomePage() {
return (
<div>
<Header /> {/* หลังคา */}
<HeroSection /> {/* ห้องโถง */}
<ProductGrid /> {/* ห้องแสดงสินค้า */}
<Testimonials /> {/* ห้องรีวิว */}
<Footer /> {/* ฐาน */}
</div>
);
}

🔄 State — สถานะของห้อง

Section titled “🔄 State — สถานะของห้อง”
function LightSwitch() {
const [isOn, setIsOn] = useState(false);
return (
<button onClick={() => setIsOn(!isOn)}>
{isOn ? '💡 เปิด' : '🔌 ปิด'}
</button>
);
}

State = สถานะปัจจุบันของห้อง เช่น ไฟเปิด/ปิด ประตูล็อก/ไม่ล็อก

🚀 Next.js — ผู้รับเหมาครบวงจร

Section titled “🚀 Next.js — ผู้รับเหมาครบวงจร”
Featureหน้าที่
✅ Routingไม่ต้องตั้งค่าเอง
✅ SSR/SSGSEO ดี
✅ API RoutesBackend ในตัว
✅ Image Optimizeรูปโหลดเร็ว

Material Selection (เลือกสเปกวัสดุ)

Section titled “Material Selection (เลือกสเปกวัสดุ)”
app/
├── page.tsx → หน้าแรก (/)
├── about/
│ └── page.tsx → หน้า About (/about)
├── products/
│ ├── page.tsx → รายการสินค้า (/products)
│ └── [id]/
│ └── page.tsx → สินค้าแต่ละชิ้น (/products/123)
└── layout.tsx → Layout หลัก
// Server Component (default) - SEO ดี
async function ProductList() {
const products = await fetchProducts();
return <ul>{products.map(p => <li>{p.name}</li>)}</ul>;
}
// Client Component - Interactive
'use client'
function AddToCart() {
const [count, setCount] = useState(0);
return <button onClick={() => setCount(c => c+1)}>Add ({count})</button>;
}

Architect’s Note (บันทึกสถาปนิก)

Section titled “Architect’s Note (บันทึกสถาปนิก)”
  1. อย่าใช้ ‘use client’ ทุกที่ — เสียประโยชน์ Server Components
  2. State ควรอยู่ใกล้ที่ใช้ — อย่า lift state ขึ้นสูงเกินไป
  3. แยก Components ให้เหมาะสม — ไม่เล็กไป ไม่ใหญ่ไป
  1. ใช้ Server Components เป็นหลัก
  2. แยก Components ตามหน้าที่
  3. ใช้ TypeScript กับ React เสมอ