ข้ามไปยังเนื้อหา

Hooks In Depth

hook คือ function ที่ชื่อขึ้นต้นด้วย use ซึ่งให้ component “hook เข้าไป” ใช้ feature ของ React — state, lifecycle, context — ได้โดยที่ยังเป็น function ธรรมดา ก่อนมี hooks มีแต่ class component เท่านั้นที่ถือ state ได้ hooks นำพลังนั้นมาให้ function โดยไม่ต้องเขียน boilerplate ของ class และไม่ทำลาย model UI = f(state)

ทริกคือ React จับคู่ hook แต่ละตัวกับ slot ในหน่วยความจำส่วนตัวของ component โดยจับคู่ ตามลำดับการเรียก การตัดสินใจออกแบบข้อเดียวนี้อธิบาย Rules of Hooks ได้ทั้งหมด และเป็นเหตุผลที่ hooks ดูเหมือนเวทมนตร์จนกว่าคุณจะเห็นกลไกข้างใน

บทเรียนสิ่งที่คุณจะได้เรียน
useState & updatesstate, batching (รวมถึงข้าม await), updater function กับ Strict Mode double-invoke, lazy init, immutability
useEffect & effectsการ sync กับ external system, ลำดับการรัน effect, useEffectEvent (19.2) และการ fetch แบบ abort-safe
useRef & the DOMmutable value, DOM ref, ref-เป็น-prop ใน React 19, ref callback cleanup และ useImperativeHandle
Memoization & the compileruseMemo/useCallback/memo, การอ่าน React Compiler output จริง และเมื่อไร manual memoization ยังจำเป็น
Rules & custom hooksทำไม rules ถึงมี, error จริงเมื่อทำผิดกฎ, custom hook ที่ return แบบ stable และข้อยกเว้น use
useId & hook อื่น ๆuseId, useSyncExternalStore, initialValue ของ useDeferredValue, useDebugValue และ useInsertionEffect
flowchart LR
  render["component renders"] --> h1["useState → slot 1"]
  render --> h2["useState → slot 2"]
  render --> h3["useEffect → slot 3"]
  h1 --> note["order must be identical
every render"]
  h2 --> note
  h3 --> note
hook ถูกจับคู่กับ memory slot ตามลำดับการเรียก

React ไม่รู้ ชื่อ hook ของคุณ — React รู้แค่ ลำดับ ที่คุณเรียก ในทุก render useState ตัวแรก map ไป slot 1, ตัวที่สองไป slot 2 ไปเรื่อย ๆ นี่คือเหตุผลที่คุณห้ามเรียก hook แบบมีเงื่อนไข ถ้าข้ามไปตัวหนึ่ง hook ที่เหลือทั้งหมดจะเลื่อนไปอยู่ slot ผิด จำภาพนี้ไว้แล้วทั้งโมดูลจะเข้าที่

hook คืออะไร?
React จับคู่การเรียก hook กับ state ที่ถูกต้องได้อย่างไร?
ทำไม hook ถึงให้ function ธรรมดามี state และ lifecycle ได้?