ရိုးရိုးလေး ရှင်းပြမယ်
ရိုးရိုးလေး ရှင်းရရင်
စားသောက်ဆိုင် တစ်ဆိုင်မှာ waiter တွေက မီးဖိုချောင်ထဲ ဝင်ပြီး ကိုယ်တိုင် ဟင်းမချက်ပါဘူး။ "စားပွဲ 5 က ထမင်းကြော် တစ်ပွဲ မှာတယ်" လို့ order စာရွက် ပေးရုံပါပဲ။ ဟင်းချက်ပုံ စည်းမျဉ်းအားလုံးကို စားဖိုမှူး တစ်ယောက်တည်းက သိပြီး ချက်ပေးပါတယ်။
useReducer က ဒီပုံစံပါ။ Event handler တွေက waiter ဖြစ်ပြီး dispatch({ type: 'added', text }) လို action (order စာရွက်) ကိုပဲ ပို့ပါတယ်။ Reducer function က စားဖိုမှူးပါ — လက်ရှိ state နဲ့ action ကို ကြည့်ပြီး state အသစ်ကို ပြန်ပေးပါတယ်။ State ဘယ်လို ပြောင်းလဲလဲဆိုတဲ့ စည်းမျဉ်းတွေ အားလုံး တစ်နေရာတည်းမှာ ရှိသွားပါတယ်။
Problem → Why → Solution
ပြဿနာ: update logic ပြန့်ကျဲပြီး tick လုပ်တာ screen ပေါ် မပေါ်
Task app တစ်ခုမှာ handler တစ်ခုစီက setTasks ကို ကိုယ့်နည်းကိုယ့်ဟန်နဲ့ ခေါ်ပါတယ်။ Feature တစ်ခု ထပ်တိုးတိုင်း update logic ပါတဲ့ handler အသစ် တစ်ခု ထပ်လာပါတယ်။ handleToggle က task object ကို တိုက်ရိုက် ပြင်ပြီး array ဟောင်းကိုပဲ setTasks ဆီ ပြန်ပေးလို့ checkbox ကို နှိပ်ရင် screen ပေါ်မှာ ဘာမှ မပြောင်းပါဘူး၊ နောက်ထပ် render တစ်ခု တခြားအကြောင်းနဲ့ ဖြစ်မှ ရုတ်တရက် ပေါ်လာပါတယ်။
function TaskApp() {
const [tasks, setTasks] = useState([]);
const [nextId, setNextId] = useState(1);
function handleAdd(text) {
setTasks([...tasks, { id: nextId, text, done: false }]);
setNextId(nextId + 1);
}
function handleToggle(id) {
const task = tasks.find((t) => t.id === id);
task.done = !task.done; // mutates the existing object
setTasks(tasks); // same array: React skips the re-render
}
function handleClearDone() {
setTasks(tasks.filter((t) => !t.done));
}
// ...every new feature adds another handler with its own update logic
}ဘာကြောင့် ဒီလို ဖြစ်တာလဲ
React က state အသစ်ကို Object.is နဲ့ အဟောင်းနဲ့ နှိုင်းယှဉ်ပါတယ်။ Array တူတူကို ပြန်ပေးရင် "ဘာမှ မပြောင်းဘူး" လို့ ယူဆပြီး re-render ကို ကျော်ပါတယ်။ Logic တွေ handler အများကြီးထဲ ပြန့်နေတော့ ဒီလို mutation မျိုးကို ရှာရခက်ပါတယ်။ Reducer တစ်ခုထဲ စုထားရင် update rule တိုင်းကို တစ်နေရာထဲမှာ ဖတ်လို့ရပြီး test လည်း ရေးလို့ ရပါတယ်။
Core concept: handler က ဘာဖြစ်လဲ ပြော၊ reducer က ဘယ်လို ပြောင်းမလဲ ဆုံးဖြတ်
const [state, dispatch] = useReducer(reducer, initialState); က useState လိုပဲ လက်ရှိ state ကို ပေးပေမယ့် setter အစား dispatch function ကို ပေးပါတယ်။ Handler တွေက dispatch({ type: 'added', id, text }) လို action object တစ်ခု ပို့ပါတယ်။ Action ရဲ့ type ကို "user ဘာလုပ်ခဲ့လဲ" ဆိုတဲ့ နာမည်နဲ့ ပေးပါ (added, toggled, cleared_done)၊ set_tasks လို "state ကို ဘယ်လို ပြင်မလဲ" ဆိုတဲ့ ညွှန်ကြားချက် မဟုတ်ပါဘူး။ React က reducer(currentState, action) ကို ခေါ်ပြီး ပြန်လာတဲ့ value ကို နောက် render ရဲ့ state အဖြစ် သုံးပါတယ်။
Reducer က pure function ဖြစ်ရပါမယ်။ Input တူရင် output တူရပြီး state ကို မပြင်ရ — array အသစ်အတွက် [...items, newItem], map(), filter() ကို၊ object အသစ်အတွက် { ...item, done: true } ကို သုံးပါ။ fetch, setTimeout, Math.random(), Date.now() လို side effect နဲ့ မတည်ငြိမ်တဲ့ value တွေကို reducer ထဲမှာ မသုံးပါနဲ့၊ id လိုမျိုး value တွေကို handler ထဲမှာ ထုတ်ပြီး action ထဲ ထည့်ပို့ပါ။ Development ရဲ့ Strict Mode က impurity ကို ဖော်ဖို့ reducer ကို နှစ်ခါ ခေါ်ပါတယ်။ မသိတဲ့ action type ကို default case မှာ throw လုပ်ထားရင် စာလုံးပေါင်း မှားတာကို ချက်ချင်း သိပါတယ်။
dispatch ပြီးတာနဲ့ state variable က ချက်ချင်း မပြောင်းပါဘူး — လက်ရှိ handler ထဲမှာ state က ဒီ render ရဲ့ snapshot အဟောင်းပဲ ဖြစ်ပြီး value အသစ်ကို နောက် render မှာမှ မြင်ရပါတယ်။ Reducer က state အဟောင်းကို အတိအကျ ပြန်ပေးရင် React က re-render ကို ကျော်နိုင်ပါတယ်။ dispatch function ရဲ့ identity က render တိုင်း မပြောင်းလို့ child တွေဆီ ပို့ရတာ လုံခြုံပါတယ်။
Reducer တစ်ခုက React ကို import တောင် မလုပ်တဲ့ JavaScript function ရိုးရိုးပါ။ ဒါကြောင့် state တစ်ခုနဲ့ action တွေ ပေးပြီး ရလဒ်ကို စစ်တဲ့ unit test တွေကို browser မလိုဘဲ ရေးလို့ရပါတယ်။
- Handler က action ကို dispatch
- React က reducer(state, action) ခေါ်
- Reducer က state အသစ် return
- နောက် render မှာ state အသစ်
Handler က "ဘာဖြစ်လဲ" ပြောပြီး reducer က "ဘယ်လို ပြောင်းမလဲ" ဆုံးဖြတ်ပါတယ်။
အထွေထွေ ပုံစံ
function reducer(state, action) {
switch (action.type) {
case 'something_happened':
return { ...state, field: action.payload }; // new object, no mutation
default:
throw new Error('Unknown action: ' + action.type);
}
}
const [state, dispatch] = useReducer(reducer, initialState);
dispatch({ type: 'something_happened', payload: value });Reducer က action.type ပေါ်မူတည်ပြီး state အသစ်ကို return ပြန်ပါတယ်။ Component ထဲမှာ useReducer က state နဲ့ dispatch ကို ပေးပြီး handler တွေက dispatch ကနေ action ပို့ပါတယ်။
Example: reducer နဲ့ counter
Counter ရဲ့ update rule နှစ်ခု (increment, reset) က component အပြင်က reducer ထဲမှာ ရှိပါတယ်။ Button တွေက state ကို တိုက်ရိုက် မပြင်ဘဲ action ပဲ dispatch လုပ်ပါတယ်။ Counter တစ်ခုအတွက်ဆိုရင် useState နဲ့လည်း လုံလောက်ပေမယ့် ပုံစံကို ရှင်းရှင်းလင်းလင်း မြင်ရဖို့ အသေးဆုံး ဥပမာကို ရွေးထားတာပါ။
import { useReducer } from 'react';
function reducer(state, action) {
switch (action.type) {
case 'increment': return { count: state.count + 1 };
case 'reset': return { count: 0 };
default: throw Error('Unknown action: ' + action.type);
}
}
export default function Counter() {
const [state, dispatch] = useReducer(reducer, { count: 0 });
return <>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>Add</button>
<button onClick={() => dispatch({ type: 'reset' })}>Reset</button>
</>;
}Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်
- Line 3
function reducer(state, action) {Component အပြင်မှာ ရှိလို့ props ဒါမှမဟုတ် component variable တွေကို မမှီခိုဘဲ state နဲ့ action ကိုပဲ ကြည့်ပါတယ်။ ဒါကြောင့် test လုပ်ရ လွယ်ပါတယ်။
- Line 5
case 'increment': return { count: state.count + 1 };state.count++ လို မပြင်ဘဲ object အသစ်ကို return ပြန်ပါတယ်။ React က object အသစ်ကို မြင်လို့ re-render လုပ်ပါတယ်။
- Line 7
default: throw Error('Unknown action: ' + action.type);dispatch({ type: 'incremnt' }) လို စာလုံးပေါင်း မှားရင် state က တိတ်တိတ်လေး မပြောင်းနေမယ့်အစား ချက်ချင်း error တက်ပါတယ်။
- Line 12
const [state, dispatch] = useReducer(reducer, { count: 0 });Reducer နဲ့ initial state ကို ပေးပြီး လက်ရှိ state နဲ့ dispatch ကို ပြန်ရပါတယ်။
- Line 15
<button onClick={() => dispatch({ type: 'increment' })}>Add</button>Button က "increment ဖြစ်ခဲ့တယ်" လို့ပဲ ပြောပါတယ်၊ count ကို ဘယ်လို တွက်မလဲ မသိပါဘူး။
Count: 0 နဲ့ Add, Reset button နှစ်ခု ပေါ်ပါတယ်။ Add နှိပ်တိုင်း count တစ်တိုးပြီး (Count: 1, Count: 2 ...) Reset နှိပ်ရင် Count: 0 ပြန်ဖြစ်ပါတယ်။useState နဲ့ useReducer ရွေးချယ်ခြင်း
| အခြေအနေ | useState | useReducer |
|---|---|---|
| State ပုံစံ | Boolean, string, number တစ်ခု | ဆက်စပ်နေတဲ့ field များစွာ |
| Update လမ်းကြောင်း | တစ်ခု နှစ်ခု | Event အမျိုးမျိုးက တူညီ state ကို ပြင် |
| Debug လုပ်ပုံ | setState ခေါ်တဲ့နေရာတိုင်း လိုက်ရှာ | Reducer ထဲမှာ action ကို log ထုတ် |
| Test | Component နဲ့ တွဲစစ် | Reducer ကို သီးခြား unit test |
App ကြီးလာရင် reducer ကို context နဲ့ တွဲသုံးပါတယ်။ State နဲ့ dispatch ကို context နှစ်ခု ခွဲထားလို့ tree ရဲ့ ဘယ်နေရာကမဆို action dispatch လုပ်လို့ရပြီး props drilling မလိုတော့ပါဘူး။ dispatch က မပြောင်းလို့ dispatch context ကိုပဲ ဖတ်တဲ့ component တွေက state ပြောင်းတာကြောင့် အဲဒီ context ကနေ re-render မဖြစ်ပါဘူး။
import { createContext, useContext, useReducer } from 'react';
import { tasksReducer } from './tasksReducer.js';
const TasksContext = createContext(null);
const TasksDispatchContext = createContext(null);
export function TasksProvider({ children }) {
const [tasks, dispatch] = useReducer(tasksReducer, []);
return (
<TasksContext value={tasks}>
<TasksDispatchContext value={dispatch}>{children}</TasksDispatchContext>
</TasksContext>
);
}
export const useTasks = () => useContext(TasksContext);
export const useTasksDispatch = () => useContext(TasksDispatchContext);လက်တွေ့ project တွေမှာ
Real project တွေမှာ ဘယ်လို သုံးလဲ
Shopping cart, step များတဲ့ checkout wizard, drag-and-drop board, undo/redo ပါတဲ့ editor လို state ပြောင်းလမ်း များတဲ့ feature တွေမှာ reducer ကို သုံးကြပါတယ်။ Action log တစ်ခုစီက user ဘာလုပ်ခဲ့လဲ အစဉ်လိုက် ပြနေလို့ bug report တစ်ခု ရလာရင် action sequence ကို ပြန် run ကြည့်ပြီး ပြဿနာကို ပြန်ဖြစ်အောင် လုပ်လို့ ရပါတယ်။ Redux (Redux Toolkit) က ဒီ reducer + action ပုံစံကို app တစ်ခုလုံးအတွက် store တစ်ခုအဖြစ် ချဲ့ထားတာ ဖြစ်ပြီး useReducer က component တစ်ခု ဒါမှမဟုတ် feature တစ်ခုအတွက် အသေးစား ပုံစံလို့ မြင်လို့ရပါတယ်။
Team တွေက reducer ကို tasksReducer.js လို file သီးသန့်မှာ ထားပြီး Vitest ဒါမှမဟုတ် Jest နဲ့ action တစ်ခုချင်းစီကို test လုပ်ကြပါတယ်။ TypeScript project တွေမှာ action တွေကို discriminated union type အဖြစ် ကြေညာပြီး case တစ်ခု ကျန်ခဲ့ရင် compiler က သတိပေးအောင် လုပ်ကြပါတယ်။ Nested state ကို immutable update လုပ်ရတာ ရှည်လာရင် Immer library ကို သုံးကြတာလည်း တွေ့ရပါတယ်။
အမှားများ
အဖြစ်များတဲ့ အမှားတွေ
1. Reducer ထဲမှာ state ကို တိုက်ရိုက် ပြင်တာ
case 'added': state.push(action.task); return state; က array တူတူကို ပြန်ပေးလို့ React က ပြောင်းလဲမှုကို မမြင်ဘဲ re-render ကို ကျော်နိုင်ပါတယ်။ return [...state, action.task]; လို array အသစ် ပြန်ပေးပါ။
2. Reducer ထဲမှာ side effect လုပ်တာ
Reducer ထဲမှာ fetch ခေါ်တာ၊ localStorage ရေးတာ၊ crypto.randomUUID() နဲ့ id ထုတ်တာက Strict Mode မှာ နှစ်ခါ ဖြစ်ပြီး ရလဒ်တွေ မတူတော့ပါဘူး။ Side effect တွေကို handler ဒါမှမဟုတ် effect ထဲ ရွှေ့ပြီး id ကို action ထဲ ထည့်ပို့ပါ။
3. dispatch ပြီးတာနဲ့ state အသစ်ကို ဖတ်ဖို့ ကြိုးစားတာ
dispatch({ type: 'added', task }); console.log(state.length); က task မထည့်ခင် အရေအတွက်ကိုပဲ ပြပါတယ်။ ချက်ချင်း လိုအပ်ရင် reducer(state, action) ကို ကိုယ်တိုင် ခေါ်ပြီး တွက်ပါ၊ ဒါမှမဟုတ် နောက် render ရဲ့ state ကို သုံးပါ။
Best Practices
အကောင်းဆုံး အလေ့အကျင့်များ
- Action တစ်ခုက user ရဲ့ လုပ်ဆောင်ချက် တစ်ခုနဲ့ ကိုက်ပါစေ — field ငါးခု ပြောင်းရင်တောင် form submit တစ်ခုအတွက် set_field action ငါးခု မဟုတ်ဘဲ submitted action တစ်ခုပဲ dispatch လုပ်ပါ။
- Reducer နဲ့ action type တွေကို component file အပြင် သီးခြား file မှာ ထားပြီး action တစ်ခုစီအတွက် test တစ်ခုစီ ရေးပါ။
- Development မှာ reducer ရဲ့ ထိပ်မှာ console.log(action) ခဏ ထည့်ကြည့်ရင် state ဘယ်လို ပြောင်းသွားလဲ အစဉ်လိုက် မြင်ရပါတယ်။
- State အားလုံးကို reducer ထဲ အတင်း မထည့်ပါနဲ့ — input focus လို တခြားနဲ့ မဆက်စပ်တဲ့ local state အတွက် useState က ပိုသင့်တော်ပါတယ်။
Mini challenge
Mini challenge: shopping cart reducer
Cart item တွေကို စီမံတဲ့ pure reducer နဲ့ total တွက်တဲ့ helper တစ်ခု ရေးပြီး useReducer နဲ့ CartPage component မှာ ချိတ်ပါ။ Reducer ကို React မပါဘဲ စမ်းလို့ ရရပါမယ်။
- Action လေးမျိုး: added (product)၊ quantity_changed (id, qty — 0 ဆိုရင် item ကို ဖယ်)၊ removed (id)၊ cleared
- added က ရှိပြီးသား product ဆိုရင် qty ကို 1 တိုးပြီး မရှိရင် qty: 1 နဲ့ ထည့်ရမယ်
- State ကို ဘယ်တော့မှ မပြင်ရ၊ မသိတဲ့ action ဆိုရင် error ပစ်ရမယ်
- cartTotal(items) က price × qty ပေါင်းလဒ်ကို ပြန်ပေးရမယ်၊ CartPage က total နဲ့ empty message ကို ပြရမယ်
import { useReducer } from 'react';
export function cartReducer(items, action) {
switch (action.type) {
// TODO: 'added' -> +1 qty if present, else append with qty 1
// TODO: 'quantity_changed' -> set qty; remove the item when qty <= 0
// TODO: 'removed' -> drop the item with action.id
// TODO: 'cleared' -> empty cart
default:
// TODO: throw for unknown actions
}
}
export function cartTotal(items) {
// TODO: sum of price * qty
}
export default function CartPage() {
// TODO: useReducer with one Green tea (price 4, qty 2) to start
// TODO: list items with "-" and "Remove" buttons, an "Add cake" button,
// a "Clear" button, "Total: N USD", and an empty-cart message
}ရလဒ်: စစချင်း: Green tea x 2, Total: 8 USD Add cake နှိပ်ပြီး: Cake x 1 ထပ်ပေါ်ပြီး Total: 14 USD Green tea ရဲ့ - ကို နှစ်ခါ နှိပ်ရင် Green tea ပျောက်ပြီး Total: 6 USD Clear နှိပ်ရင်: Your cart is empty. နဲ့ Total: 0 USD Reducer ကို တိုက်ရိုက် စမ်းရင် dispatch({ type: 'refunded' }) လို action က "Unknown action: refunded" error ပစ်ပါတယ်။
အရိပ်အမြွက် ကြည့်ရန်
added case ထဲမှာ const နဲ့ variable ကြေညာဖို့ case ကို { } နဲ့ ထုပ်ပါ။ qty ပြောင်းဖို့ items.map(item => item.id === id ? { ...item, qty } : item) ပုံစံကို သုံးပါ။ Reducer ကို node ထဲမှာ action sequence တစ်ခုနဲ့ ခေါ်ပြီး ရလဒ်ကို console.log နဲ့ စစ်ကြည့်ပါ။
အဖြေ ကြည့်ရန်
import { useReducer } from 'react';
export function cartReducer(items, action) {
switch (action.type) {
case 'added': {
const exists = items.some((item) => item.id === action.product.id);
if (!exists) return [...items, { ...action.product, qty: 1 }];
return items.map((item) =>
item.id === action.product.id ? { ...item, qty: item.qty + 1 } : item,
);
}
case 'quantity_changed':
if (action.qty <= 0) return items.filter((item) => item.id !== action.id);
return items.map((item) =>
item.id === action.id ? { ...item, qty: action.qty } : item,
);
case 'removed':
return items.filter((item) => item.id !== action.id);
case 'cleared':
return [];
default:
throw new Error('Unknown action: ' + action.type);
}
}
export function cartTotal(items) {
return items.reduce((sum, item) => sum + item.price * item.qty, 0);
}
const CAKE = { id: 'cake', name: 'Cake', price: 6 };
const START = [{ id: 'tea', name: 'Green tea', price: 4, qty: 2 }];
export default function CartPage() {
const [items, dispatch] = useReducer(cartReducer, START);
return (
<section>
{items.length === 0 && <p>Your cart is empty.</p>}
<ul>
{items.map((item) => (
<li key={item.id}>
{item.name} x {item.qty}{' '}
<button type="button" onClick={() =>
dispatch({ type: 'quantity_changed', id: item.id, qty: item.qty - 1 })}>
-
</button>
<button type="button"
onClick={() => dispatch({ type: 'removed', id: item.id })}>
Remove
</button>
</li>
))}
</ul>
<button type="button" onClick={() => dispatch({ type: 'added', product: CAKE })}>
Add cake
</button>
<button type="button" onClick={() => dispatch({ type: 'cleared' })}>Clear</button>
<p>Total: {cartTotal(items)} USD</p>
</section>
);
}Quick Quiz 1 / 3
Quick Quiz 2 / 3
Quick Quiz 3 / 3
မှတ်ထားရမယ့် အချက်များ
- useReducer(reducer, initialState) က [state, dispatch] ပေးပြီး handler တွေက "ဘာဖြစ်ခဲ့လဲ" ကို action အဖြစ် dispatch လုပ်ပါတယ်။
- Reducer က pure ဖြစ်ရပါမယ်: state ကို မပြင်ဘဲ object/array အသစ် ပြန်ပေး၊ side effect မလုပ်၊ မသိတဲ့ action ကို throw လုပ်ပါ။
- dispatch ပြီးတာနဲ့ state variable မပြောင်းပါဘူး — value အသစ်ကို နောက် render မှာ မြင်ရပါတယ်။
- Reducer ကို ရိုးရိုး function အဖြစ် test လုပ်ပြီး app ကြီးလာရင် state နဲ့ dispatch ကို context နှစ်ခုနဲ့ ပို့ပါ။