Action คือ object ธรรมดาที่อธิบาย สิ่งที่เกิดขึ้น; reducer คือ pure function ที่ใช้ state ปัจจุบันและ action แล้วส่งกลับ state ถัดไป ร่วมกันพวกมันจะใช้งาน state transitions ที่คาดเดาได้
Actions — อธิบาย events
{ : , : { : , : } }
{ : , : }
Action คือ object ธรรมดาที่อธิบาย สิ่งที่เกิดขึ้น; reducer คือ pure function ที่ใช้ state ปัจจุบันและ action แล้วส่งกลับ state ถัดไป ร่วมกันพวกมันจะใช้งาน state transitions ที่คาดเดาได้
{ : , : { : , : } }
{ : , : }
Actions ไม่ได้ ทำอะไร — พวกมันเป็นคำอธิบายแบบ declarative ของ events การตั้งชื่อในรูปแบบ past-tense ("added", "toggled") สะท้อนว่าพวกมันบันทึกสิ่งที่เกิดขึ้น
function todosReducer(state = [], action) {
switch (action.type) {
case "todos/added":
return [...state, action.payload]; // new array
case "todos/toggled":
return state.map(t => // new array, new object for the changed one
t.id === action.payload ? { ...t, done: !t.done } : t
);
default:
return state; // unknown action → unchanged
}
}
ลายเซนต์ของ reducer คือ (state, action) => newState ต้องส่งกลับ state object/array ใหม่ (immutably) ไม่ควร mutate input เลย
Pure function: (1) ส่งกลับ output เดียวกันสำหรับ input เดียวกัน และ (2) ไม่มี side effects Reducers ต้องปฏิบัติตามกฎทั้งสองข้อ:
// ❌ NOT pure — breaks everything
function badReducer(state, action) {
state.value++; // ❌ mutates input (breaks change detection, time-travel)
fetch("/api/log"); // ❌ side effect (non-deterministic, untestable)
return { value: Math.random() }; // ❌ non-deterministic output
}
Purity ช่วยให้ Redux feature ที่มีลายเซนต์:
✓ Predictability — same state + action ALWAYS gives the same result
✓ Time-travel / replay — you can re-run actions to reproduce any state
✓ Testability — just call reducer(state, action) and assert; no mocks needed
✓ Change detection — returning new references lets the UI detect changes
Side effects (API calls, logging, randomness) ควรอยู่ใน middleware (thunks/sagas) หรือ effects — ไม่ควรอยู่ใน reducers
Action/reducer model คือหัวใจของ Redux-style state management และเป็นเหตุผลว่าทำไมจึงสามารถ debug และ test ได้ง่าย
ข้อกำหนด purity ไม่ได้มีความเป็นทั้งหมด: มันเป็น สิ่งที่ทำให้ time-travel debugging, action replay และ trivial unit testing เป็นไปได้ และเป็นเหตุผลว่าทำไม side effects ต้องอยู่ที่อื่น
รูปแบบการอัปเดต immutable ที่ขับเคลื่อนด้วย pure-function นี้เกิดขึ้นซ้ำในเรื่อง Redux, NgRx, useReducer และอื่นๆ — การเข้าใจมัน (และการปกครองตัวเองในการรักษา reducers ให้บริสุทธิ์) เป็นพื้นฐานสำหรับ state ที่คาดเดาได้
คลังคำถามสัมภาษณ์งาน IT พร้อมคำตอบโดยละเอียด — ตั้งแต่ระดับ Junior ถึง Senior
บริจาค