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

Foundations & Mental Model

React render UI ของคุณเป็นฟังก์ชันของ state: UI = f(state) คุณไม่ได้ update DOM เองตอนข้อมูลเปลี่ยน — คุณแค่บอกว่า UI ควรหน้าตาเป็นอย่างไร สำหรับ state ปัจจุบัน แล้ว React คิดต่อเองว่าต้องแก้ DOM น้อยที่สุดแค่ไหนเพื่อไปให้ถึงจุดนั้น

ทุกหัวข้อขั้นสูง — hooks, reconciliation, Suspense, compiler — ล้วนเป็นผลลัพธ์ของการเอาสมการเดียวนี้มาคิดอย่างจริงจัง เข้าใจ model ให้ถูก ที่เหลือก็ตามมาเอง

บทเรียนสิ่งที่คุณจะได้เรียน
Why React & the modeldeclarative เทียบกับ imperative และ UI = f(state)
JSX & elementsJSX compile เป็นอะไร และ element จริง ๆ คืออะไร
Rendering & reconciliationrender/commit phase, virtual tree และ key
State snapshot & puritystate เป็น snapshot, immutability และทำไม render ถึง pure

สองแนวคิดอธิบายเกือบทุกอย่างที่ React ทำ:

flowchart TB
  f["UI = f(state)
(you describe, React updates)"] --> render["Re-render on state change
(compute the new tree)"]
  pure["Render is pure
(no side effects, same input same output)"] --> render
  render --> recon["Reconciliation
(diff old vs new, patch the DOM)"]
สองแนวคิดที่เป็นรากฐานของทุกอย่าง
  • เพราะ UI เป็นฟังก์ชันของ state การเปลี่ยน state จึง trigger การ re-render — React รัน component ของคุณใหม่เพื่อคำนวณว่า UI ตอนนี้ควรเป็นอะไร
  • เพราะ render เป็น pure React จึงเรียก component ของคุณเมื่อไรก็ได้ batch ได้ restart ได้ หรือรันซ้ำสองครั้ง (StrictMode) — นั่นคือสิ่งที่ทำให้ concurrent features เกิดขึ้นได้

จับสองอย่างนี้ไว้ แล้ว React จะเลิกทำให้คุณประหลาดใจ

สมการหลักที่ React สร้างขึ้นมาคืออะไร?
ใน React คุณ update สิ่งที่ user เห็นอย่างไร?
ทำไม React ถึงต้องการให้ render เป็น pure?