บทที่ 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/SSG | SEO ดี |
| ✅ API Routes | Backend ในตัว |
| ✅ Image Optimize | รูปโหลดเร็ว |
Material Selection (เลือกสเปกวัสดุ)
Section titled “Material Selection (เลือกสเปกวัสดุ)”📁 Next.js App Router
Section titled “📁 Next.js App Router”app/├── page.tsx → หน้าแรก (/)├── about/│ └── page.tsx → หน้า About (/about)├── products/│ ├── page.tsx → รายการสินค้า (/products)│ └── [id]/│ └── page.tsx → สินค้าแต่ละชิ้น (/products/123)└── layout.tsx → Layout หลัก⚡ Server vs Client Components
Section titled “⚡ Server vs Client Components”// 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 (บันทึกสถาปนิก)”⚠️ ข้อควรระวัง
Section titled “⚠️ ข้อควรระวัง”- อย่าใช้ ‘use client’ ทุกที่ — เสียประโยชน์ Server Components
- State ควรอยู่ใกล้ที่ใช้ — อย่า lift state ขึ้นสูงเกินไป
- แยก Components ให้เหมาะสม — ไม่เล็กไป ไม่ใหญ่ไป
💡 Best Practices
Section titled “💡 Best Practices”- ใช้ Server Components เป็นหลัก
- แยก Components ตามหน้าที่
- ใช้ TypeScript กับ React เสมอ