Dark mode
React Rules of Hooks: เข้าใจง่าย ใช้งานได้จริง
Hooks คือฟีเจอร์สำคัญที่เปลี่ยนวิธีการเขียน React ให้โมเดิร์นและกระชับขึ้นมาก แต่การใช้ Hooks ต้องปฏิบัติตาม "กฎเหล็ก" (Rules of Hooks) เพื่อให้แอปทำงานถูกต้องและ predictable
กฎเหล็กของ React Hooks (Rules of Hooks)
1. เรียกใช้ Hooks ได้เฉพาะในระดับบนสุดของฟังก์ชันคอมโพเนนต์
- ห้าม เรียกใช้ Hooks ใน if, for, หรือฟังก์ชัน nested ใดๆ
ตัวอย่างผิด
jsx
function MyComponent() {
if (someCondition) {
const [count, setCount] = useState(0); // ❌ ผิด
}
}
ตัวอย่างถูก
jsx
function MyComponent() {
const [count, setCount] = useState(0); // ✅ ถูก
if (someCondition) {
// ...
}
}
2. เรียกใช้ Hooks ได้เฉพาะในฟังก์ชันคอมโพเนนต์ หรือ Custom Hook เท่านั้น
- ห้าม ใช้ Hooks ในฟังก์ชันทั่วไป คลาส หรือโค้ดนอกคอมโพเนนต์
ตัวอย่างผิด
jsx
function notAComponent() {
const [x, setX] = useState(0); // ❌ ผิด
}
ตัวอย่างถูก
jsx
function MyComponent() {
const [x, setX] = useState(0); // ✅ ถูก
}
function useCustomHook() {
const [y, setY] = useState(0); // ✅ ถูก (Custom Hook)
}
เหตุผลเบื้องหลัง
- React ใช้ลำดับการเรียก Hooks เพื่อจับคู่ state กับคอมโพเนนต์ ถ้าเรียกไม่ตรงลำดับ (เช่นใน if/for) จะเกิด bug ที่ตรวจจับยาก
- Hooks ออกแบบมาให้ใช้กับ function component เท่านั้น ไม่รองรับ class component
เปรียบเทียบกับ Class Component
Class Component | Function + Hooks |
---|---|
this.state | useState |
this.setState | setState |
Lifecycle methods (componentDidMount , etc.) | useEffect |
Hooks ทำให้โค้ดกระชับขึ้น ไม่ต้องใช้ class และ this อีกต่อไป
ตรวจสอบกฎด้วย eslint-plugin-react-hooks
แนะนำให้ติดตั้ง eslint-plugin-react-hooks เพื่อเตือนเมื่อใช้ Hooks ผิดกฎ
bash
npm install eslint-plugin-react-hooks --save-dev
เพิ่ม config ใน .eslintrc
:
json
{
"plugins": ["react-hooks"],
"rules": {
"react-hooks/rules-of-hooks": "error", // ตรวจสอบกฎเหล็ก
"react-hooks/exhaustive-deps": "warn" // เตือน dependency ของ useEffect
}
}
ข้อควรระวัง & Best Practices
- Custom Hook ต้องขึ้นต้นด้วย
use
เสมอ เช่นuseAuth
- อย่าใช้ Hooks ใน callback หรือ utility function ที่ไม่ใช่คอมโพเนนต์
- ถ้าใช้ useEffect ให้ใส่ dependency array ให้ถูกต้อง
สรุป
- ทำตาม Rules of Hooks = โค้ดปลอดภัยและ predictable
- ใช้ eslint-plugin-react-hooks ช่วยตรวจสอบ
- Hooks = เขียน React แบบใหม่ที่ง่ายและยืดหยุ่นกว่าเดิม