ရိုးရိုးလေး ရှင်းပြမယ်
ရိုးရိုးလေး ရှင်းရရင်
Component တစ်ခုက server ပေါ်က blog post တစ်ပုဒ်ကို ပြချင်တယ်ဆိုပါစို့။ Data က ချက်ချင်း မရောက်ပါဘူး။ Network က အချိန်ယူတယ်၊ တစ်ခါတလေ fail ဖြစ်တယ်။ ဒါကြောင့် screen က အခြေအနေ သုံးမျိုးကို ပြနိုင်ရပါမယ်: "စောင့်နေတုန်း"၊ "မှားသွားပြီ"၊ "ရပြီ"။
စားသောက်ဆိုင်မှာ order မှာတာနဲ့ တူပါတယ်။ Order ပေးပြီးရင် ဝိတ်တာက "ချက်နေပါတယ်" လို့ ပြောတယ်၊ ဟင်းကုန်သွားရင် "မရတော့ပါဘူး" လို့ ပြောတယ်၊ နောက်ဆုံး ပန်းကန်ရောက်လာတယ်။ React မှာ order ပေးတဲ့အလုပ်ကို useEffect ထဲမှာ လုပ်ပြီး ဝိတ်တာရဲ့ အဖြေသုံးမျိုးကို useState နဲ့ မှတ်ထားပါတယ်။
Problem → Why → Solution
ပြဿနာ: နောက်ကျမှ ရောက်လာတဲ့ response အဟောင်း
အောက်က Post component က postId prop ပြောင်းတိုင်း fetch ပြန်လုပ်ပါတယ်။ ကြည့်ရတာ ပြဿနာမရှိပါဘူး။ ဒါပေမယ့် user က post 1 ကို နှိပ်ပြီး ချက်ချင်း post 2 ကို နှိပ်လိုက်တယ်ဆိုပါစို့။ Post 1 ရဲ့ request က နှေးပြီး post 2 ရဲ့ request က မြန်ရင် post 2 ရဲ့ data အရင်ရောက်၊ ပြီးမှ post 1 ရဲ့ data ရောက်လာပြီး ဖုံးအုပ်ပစ်ပါတယ်။
ရလဒ်က URL နဲ့ selected tab က post 2 ကို ပြနေပေမယ့် title က post 1 ဖြစ်နေတာပါ။ Server က 404 ပြန်ရင်လည်း ဒီ code က error page ရဲ့ JSON ကို post တစ်ပုဒ်လို သဘောထားပြီး ဆက်သုံးပါတယ်။
function Post({ postId }) {
const [post, setPost] = useState(null);
useEffect(() => {
fetch(`/api/posts/${postId}`)
.then((res) => res.json()) // no res.ok check
.then((data) => setPost(data)); // whichever response lands LAST wins
}, [postId]); // no cleanup function
return <h1>{post?.title}</h1>;
}ဘာကြောင့် ဒီလိုဖြစ်တာလဲ
Network request တွေက မှာထားတဲ့ အစီအစဉ်အတိုင်း ပြန်မရောက်ပါဘူး။ Effect တစ်ခုစီက သူ့ကိုယ်ပိုင် request ကို စတင်ပြီး "ငါ့ရဲ့ postId က ဟောင်းသွားပြီ" ဆိုတာကို မသိပါဘူး။ Cleanup function မရှိရင် React က effect အဟောင်းကို ရပ်ခိုင်းဖို့ နည်းလမ်းမရှိပါဘူး။ ဒါ့အပြင် fetch() က network ပြတ်တာမျိုးမှာပဲ reject ဖြစ်ပြီး 404/500 response တွေမှာ ပုံမှန်အတိုင်း resolve ဖြစ်ပါတယ်။
Core concept: fetch ကို effect တစ်ခုအဖြစ် synchronize လုပ်ခြင်း
useEffect ထဲက fetch ကို "component render ပြီးရင် တစ်ခါ run တဲ့ code" လို့ မမြင်ပါနဲ့။ "ဒီ postId အတွက် server နဲ့ synchronize လုပ်ထားပါ" လို့ မြင်ပါ။ postId ပြောင်းတိုင်း React က effect အဟောင်းရဲ့ cleanup ကို အရင် run ပြီးမှ effect အသစ်ကို run ပါတယ်။ ဒီ အစီအစဉ်ကို အသုံးချပြီး request အဟောင်းကို ပိတ်ပစ်ရပါမယ်။ အဆင့်လေးဆင့် ရှိပါတယ်။
၁။ State သုံးမျိုးကို model လုပ်ပါ
Loading၊ error၊ data ကို state အနေနဲ့ ကိုင်ထားပြီး render မှာ တစ်ခုစီအတွက် UI ပြန်ပေးပါ။ Data ရောက်မလာခင် post.title ကို ဖတ်ရင် null ပေါ်မှာ property ဖတ်တဲ့ error တက်ပါလိမ့်မယ်။
၂။ response.ok ကို ကိုယ်တိုင်စစ်ပါ
fetch() က server ဆီက ဘယ် response မဆို ရရင် resolve ဖြစ်ပါတယ်။ Status 200-299 မဟုတ်ရင် throw လုပ်ပြီး catch ထဲကို ပို့ပေးရတာ သင့်တာဝန်ပါ။
၃။ Cleanup မှာ request အဟောင်းကို ပိတ်ပါ
Effect ထဲမှာ let ignore = false ကို ကြေညာပြီး cleanup မှာ true ပြောင်းပါ။ setState မလုပ်ခင် ignore ကို စစ်ရင် response အဟောင်းက state ကို မထိနိုင်တော့ပါဘူး။ AbortController.abort() ကိုပါ ခေါ်ရင် browser က download ကိုပါ ရပ်ပေးလို့ bandwidth သက်သာပါတယ်။
၄။ Strict Mode ရဲ့ နှစ်ခါ run ခြင်းကို နားလည်ပါ
Development မှာ Strict Mode က component ကို mount၊ unmount၊ ပြန် mount လုပ်ပြီး effect ကို နှစ်ခါ run ပါတယ်။ Network tab မှာ ပထမ request က canceled ဖြစ်နေရင် cleanup အလုပ်လုပ်နေတယ်ဆိုတဲ့ သက်သေပါ၊ bug မဟုတ်ပါဘူး။ Production မှာ ဒီလို ထပ် run တာ မရှိပါဘူး။
function Post({ postId }) {
const [result, setResult] = useState({ id: null, post: null, error: '' });
useEffect(() => {
let ignore = false;
const controller = new AbortController();
fetch(`/api/posts/${postId}`, { signal: controller.signal })
.then((res) => {
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
})
.then((post) => { if (!ignore) setResult({ id: postId, post, error: '' }); })
.catch((err) => {
if (!ignore) setResult({ id: postId, post: null, error: err.message });
});
return () => { ignore = true; controller.abort(); };
}, [postId]);
if (result.id !== postId) return <p>Loading…</p>;
if (result.error) return <p role="alert">{result.error}</p>;
return <h1>{result.post.title}</h1>;
}ဒီ version မှာ loading ကို သီးသန့် state အဖြစ် မသိမ်းပါဘူး။ result.id က လက်ရှိ postId နဲ့ မတူရင် "ဒီ post ရဲ့ data မရောက်သေးဘူး" လို့ derive လုပ်ပါတယ်။ ဒါကြောင့် postId ပြောင်းတဲ့ render မှာပဲ title အဟောင်း တစ်ချက်မှ မပေါ်ဘဲ Loading… ချက်ချင်း ပေါ်ပါတယ်။ Abort လုပ်လိုက်တဲ့ request က AbortError နဲ့ reject ဖြစ်ပေမယ့် အဲဒီအချိန်မှာ ignore က true ဖြစ်နေလို့ error message အဖြစ် မပေါ်ပါဘူး။
Race without cleanup
--------------------
time --->
click post 1 request A ---------------------------> lands, sets post 1
click post 2 request B -------> lands, sets post 2
screen: Loading post 2 shown post 1 shown (WRONG)
with cleanup: clicking post 2 runs A's cleanup -> ignore = true + abort()- postId ပြောင်းတယ်
- Cleanup က request အဟောင်းကို ပိတ်
- Effect အသစ်က request အသစ် စ
- ignore မဖြစ်သေးရင်သာ state ထည့်
Request တိုင်းက သူ့ကိုစတင်ခဲ့တဲ့ postId ကို ပိုင်ပါတယ်။ Dependency ပြောင်းသွားရင် အဲဒီ request ရဲ့ အဖြေက screen ကို မပြောင်းခွင့် မရှိတော့ပါဘူး။
အခြေခံ ပုံစံ
useEffect(() => {
let ignore = false;
const controller = new AbortController();
loadSomething(dependency, { signal: controller.signal })
.then((data) => { if (!ignore) setData(data); })
.catch((error) => { if (!ignore) setError(error); });
return () => { ignore = true; controller.abort(); };
}, [dependency]);Effect တစ်ခုက dependency value တစ်ခုအတွက် request တစ်ခုကို စတင်ပြီး cleanup က အဲဒီ request ကို ပြန်ပိတ်ပါတယ်။ setState မလုပ်ခင် ignore ကို အမြဲစစ်ပါ။
Post တစ်ပုဒ်ကို fetch လုပ်ပြီး state သုံးမျိုး ပြခြင်း
အောက်က component က URL တစ်ခုတည်းကနေ post တစ်ပုဒ်ကို mount ဖြစ်ချိန်မှာ fetch လုပ်ပါတယ်။ URL က မပြောင်းလို့ race condition မဖြစ်နိုင်ပါဘူး၊ ဒါကြောင့် ဒီ version မှာ cleanup မပါတာ လက်ခံနိုင်ပါတယ်။ ဒါပေမယ့် state သုံးမျိုး၊ response.ok စစ်တာ၊ finally ထဲမှာ loading ပိတ်တာတို့ကို သေချာ လေ့လာပါ။ ID က prop ကနေ လာတဲ့ အခါကျမှ အပေါ်က cleanup pattern လိုလာပါတယ်။
import { useEffect, useState } from 'react';
function Post() {
const [post, setPost] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
useEffect(() => {
async function loadPost() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
if (!response.ok) throw new Error('Failed to load post');
const data = await response.json();
setPost(data);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
}
loadPost();
}, []);
if (loading) return <p>Loading...</p>;
if (error) return <p>{error}</p>;
return <h1>{post.title}</h1>;
}Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်
- Loading starts as true
const [loading, setLoading] = useState(true);ပထမ render မှာ data မရှိသေးလို့ loading ကို true နဲ့ စပါတယ်။ false နဲ့ စရင် ပထမ render က post.title ကို null ပေါ်မှာ ဖတ်ပြီး crash ဖြစ်ပါမယ်။
- Turn HTTP errors into exceptions
if (!response.ok) throw new Error('Failed to load post');404 သို့မဟုတ် 500 ရရင် fetch က resolve ပဲ ဖြစ်ပါတယ်။ ဒီ line က အဲဒီ response တွေကို exception အဖြစ်ပြောင်းပြီး catch ထဲ ပို့ပေးပါတယ်။
- Store the error message
setError(err.message);Network ပြတ်တာရော HTTP error ရော နှစ်မျိုးလုံး ဒီကို ရောက်ပါတယ်။ Message ကို state ထဲ သိမ်းထားလို့ render က user ကို ပြနိုင်ပါတယ်။
- Loading ends either way
setLoading(false);finally ထဲမှာ ရှိလို့ အောင်မြင်သည်ဖြစ်စေ fail သည်ဖြစ်စေ loading ပိတ်ပါတယ်။ try နဲ့ catch နှစ်နေရာလုံးမှာ ထပ်ရေးစရာ မလိုပါဘူး။
- Run once after mount
}, []);Dependency array ဗလာက "ဒီ effect က props သို့မဟုတ် state ကို မမှီခိုဘူး" လို့ ပြောတာပါ။ URL ထဲမှာ prop တစ်ခု ပါလာတာနဲ့ အဲဒီ prop ကို array ထဲ ထည့်ပြီး cleanup ပါ ရေးရပါမယ်။
- Early returns per state
if (loading) return <p>Loading...</p>;Loading နဲ့ error ကို အရင်စစ်ပြီး return လုပ်လိုက်လို့ နောက်ဆုံး line ရောက်ချိန်မှာ post ရှိနေတာ သေချာပါတယ်။
အစမှာ Loading ပေါ်ပြီး data ရောက်လာရင် post title ပေါ်လာမယ်။ API ပြဿနာရှိရင် error message ပေါ်မယ်။Data library နဲ့ framework loader တွေ ဘာကြောင့် ရှိတာလဲ
Effect ထဲမှာ ကိုယ်တိုင် fetch လုပ်တာက သင်ယူဖို့ ကောင်းပေမယ့် app ကြီးလာရင် ထပ်ခါထပ်ခါ ရေးရတဲ့ အလုပ်တွေ အများကြီး ပေါ်လာပါတယ်။ Page တစ်ခုကနေ ထွက်ပြီး ပြန်ဝင်တိုင်း data ကို ပြန် download လုပ်ရတယ်။ Component နှစ်ခုက URL တူတူကို တစ်ပြိုင်နက် တောင်းရင် request နှစ်ခု ထွက်တယ်။ Parent က fetch ပြီးမှ child render ဖြစ်ပြီး child က ထပ် fetch လုပ်ရင် request တွေ တစ်ခုပြီးတစ်ခု တန်းစီ (waterfall) ဖြစ်သွားတယ်။
React documentation ကိုယ်တိုင်က production app တွေမှာ framework ရဲ့ data fetching ဒါမှမဟုတ် client-side cache library ကို သုံးဖို့ အကြံပြုပါတယ်။
| နည်းလမ်း | ရလာတာ | ပေးရတဲ့ အရာ |
|---|---|---|
| useEffect + fetch | Dependency မရှိ၊ အလုပ်လုပ်ပုံ အကုန်မြင်ရ | Cache၊ retry၊ dedupe ကို ကိုယ်တိုင်ရေးရ |
| TanStack Query၊ SWR | Cache၊ request ပေါင်းခြင်း၊ retry၊ refetch | Library တစ်ခုနဲ့ သူ့ cache key စည်းမျဉ်း |
| Framework loader (React Router၊ Next.js) | Render မတိုင်ခင် route data ကို ပြိုင်တူ စတင် | Framework ရဲ့ routing ပုံစံကို လိုက်ရ |
use() နဲ့ Suspense: promise ကို render ထဲမှာ ဖတ်ခြင်း
React 19 မှာ use() API ပါလာပါတယ်။ Promise တစ်ခုကို render ထဲမှာ use(promise) နဲ့ ဖတ်ရင် resolve မဖြစ်သေးသမျှ component က suspend ဖြစ်ပြီး အနီးဆုံး Suspense boundary ရဲ့ fallback ပေါ်ပါတယ်။ Promise reject ဖြစ်ရင် အနီးဆုံး error boundary က ဖမ်းပါတယ်။
အရေးကြီးတဲ့ စည်းကမ်းကတော့ promise ကို component ထဲမှာ render တိုင်း အသစ်မဖန်တီးရပါဘူး။ Render တိုင်း promise အသစ်ဖြစ်နေရင် React က ဘယ်တော့မှ ပြီးဆုံးတဲ့ အဖြေကို မမြင်ရပါဘူး။ Promise ကို framework loader၊ Server Component ဒါမှမဟုတ် cache လုပ်ထားတဲ့ library တစ်ခုက ဖန်တီးပြီး prop အဖြစ် ပေးပို့တာမျိုးကို ရည်ရွယ်ထားတာပါ။
import { Suspense, use } from 'react';
function Comments({ commentsPromise }) {
const comments = use(commentsPromise); // suspends until it resolves
return comments.map((c) => <p key={c.id}>{c.text}</p>);
}
// commentsPromise comes from a loader or a cache, not from Comments itself
<Suspense fallback={<p>Loading comments…</p>}>
<Comments commentsPromise={commentsPromise} />
</Suspense>လက်တွေ့ project တွေမှာ
လက်တွေ့ project တွေမှာ
Search box တွေမှာ race condition ကို အများဆုံး တွေ့ရပါတယ်။ User က "rea" ရိုက်ပြီး "react" ဆက်ရိုက်ရင် request နှစ်ခု ထွက်ပြီး "rea" ရဲ့ ရလဒ်က နောက်ကျရောက်လာတတ်ပါတယ်။ Cleanup ပါတဲ့ effect က အဲဒီ ရလဒ်ကို လျစ်လျူရှုပါတယ်။ Dashboard တွေမှာတော့ widget များစွာက data တူတူကို တောင်းလို့ cache library က request တစ်ခုတည်းအဖြစ် ပေါင်းပေးတာ အကျိုးများပါတယ်။
Team အများစုက fetch ကို component ထဲမှာ တိုက်ရိုက် မရေးဘဲ api.js လို file တစ်ခုထဲမှာ getPost(id, { signal }) လို function အဖြစ် ထားပါတယ်။ Base URL၊ auth header၊ response.ok စစ်တာတွေက တစ်နေရာတည်းမှာ ရှိလို့ component တွေက state သုံးမျိုးကိုပဲ ဂရုစိုက်ရပါတယ်။ Loading UI ကိုလည်း "Loading..." စာသားအစား layout မခုန်အောင် skeleton placeholder နဲ့ ပြလေ့ရှိပါတယ်။
အမှားများ
ဖြစ်လေ့ရှိတဲ့ အမှားများ
Effect function ကို async လုပ်တာ
useEffect(async () => { ... }) လို့ ရေးရင် effect က promise ကို return ပြန်ပါတယ်။ React က cleanup function ကို မျှော်လင့်ထားလို့ warning ပြပြီး cleanup လုံးဝ မရှိတော့ပါဘူး။ Example မှာလို အထဲမှာ async function တစ်ခု ကြေညာပြီး ခေါ်ပါ။
Dependency ထည့်ပြီး cleanup မေ့တာ
[postId] ကို array ထဲ ထည့်ပြီး ignore flag မထည့်ရင် problem section ထဲက race ပြန်ဖြစ်ပါတယ်။ Request က prop ဒါမှမဟုတ် state တစ်ခုကို မှီခိုတိုင်း cleanup ပါ ရေးပါ။
AbortError ကို user error အဖြစ် ပြတာ
Cleanup က abort လုပ်လိုက်တဲ့ request က catch ထဲ ရောက်လာပါတယ်။ ignore ကို မစစ်ဘဲ setError လုပ်ရင် user က tab ပြောင်းရုံနဲ့ "The user aborted a request" လို message မြင်ရပါမယ်။ ကိုယ်တိုင် ပယ်ဖျက်ခဲ့တာကို error အဖြစ် မပြပါနဲ့။
Mini challenge
User ပြောင်းလို့ရတဲ့ UserCard
Select box ကနေ user ID (1၊ 2၊ 3) ကို ရွေးလိုက်တိုင်း /api/users/:id ကနေ user ကို fetch လုပ်ပြီး name နဲ့ email ကို ပြတဲ့ UserCard ကို ရေးပါ။ User မြန်မြန် ပြောင်းရင်တောင် နောက်ဆုံးရွေးတဲ့ user ပဲ ပေါ်ရပါမယ်။
- userId ကို dependency အဖြစ် ထည့်ပြီး ignore flag နဲ့ AbortController ပါတဲ့ cleanup ရေးပါ
- response.ok မဟုတ်ရင် "HTTP 404" လို message နဲ့ throw လုပ်ပါ
- Loading ကို result.id နဲ့ userId မတူခြင်းကနေ derive လုပ်ပါ
- Error ကို role="alert" ပါတဲ့ paragraph နဲ့ ပြပါ
import { useEffect, useState } from 'react';
function UserCard({ userId }) {
// TODO: one state object { id, user, error }
useEffect(() => {
// TODO: ignore flag + AbortController
// TODO: fetch /api/users/:id, check res.ok, store user or error
// TODO: return a cleanup that ignores and aborts
}, [/* TODO */]);
// TODO: loading -> error -> name + email
}
export default function UserPicker() {
// TODO: userId state starting at 1, a <select> with 1-3, then <UserCard />
}ရလဒ်: ပထမဆုံး "Loading user…" ပေါ်ပြီး user 1 ရဲ့ name နဲ့ email ပေါ်ပါမယ်။ 2 ကနေ 3 ကို မြန်မြန်ပြောင်းရင် user 3 ပဲ ပေါ်ပြီး Network tab မှာ user 2 ရဲ့ request က canceled ဖြစ်နေပါမယ်။ မရှိတဲ့ ID ဆိုရင် "HTTP 404" alert ပေါ်ပါမယ်။
အရိပ်အမြွက် ကြည့်ရန်
Request ရဲ့ ရလဒ်ကို သိမ်းတဲ့အခါ id: userId ကိုပါ တွဲသိမ်းပါ။ Render မှာ result.id !== userId ဖြစ်နေရင် Loading ပြရုံပါပဲ။ Select ရဲ့ value က string ဖြစ်လို့ Number() နဲ့ ပြောင်းပါ။
အဖြေ ကြည့်ရန်
import { useEffect, useState } from 'react';
function UserCard({ userId }) {
const [result, setResult] = useState({ id: null, user: null, error: '' });
useEffect(() => {
let ignore = false;
const controller = new AbortController();
async function load() {
try {
const res = await fetch(`/api/users/${userId}`, { signal: controller.signal });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const user = await res.json();
if (!ignore) setResult({ id: userId, user, error: '' });
} catch (err) {
if (!ignore) setResult({ id: userId, user: null, error: err.message });
}
}
load();
return () => {
ignore = true;
controller.abort();
};
}, [userId]);
if (result.id !== userId) return <p>Loading user…</p>;
if (result.error) return <p role="alert">{result.error}</p>;
return (
<article>
<h2>{result.user.name}</h2>
<p>{result.user.email}</p>
</article>
);
}
export default function UserPicker() {
const [userId, setUserId] = useState(1);
return (
<section>
<label>
User{' '}
<select value={userId} onChange={(e) => setUserId(Number(e.target.value))}>
<option value={1}>1</option>
<option value={2}>2</option>
<option value={3}>3</option>
</select>
</label>
<UserCard userId={userId} />
</section>
);
}Quick Quiz 1 / 3
Quick Quiz 2 / 3
Quick Quiz 3 / 3
မှတ်ထားရမယ့် အချက်များ
- Fetch လုပ်တဲ့ component တိုင်းမှာ loading၊ error၊ data UI သုံးမျိုး ရှိရပါမယ်
- fetch() က 404/500 မှာ reject မဖြစ်လို့ response.ok ကို ကိုယ်တိုင် စစ်ပါ
- Request က prop/state ကို မှီခိုရင် ignore flag နဲ့ abort() ပါတဲ့ cleanup ရေးပါ
- Cache၊ dedupe၊ waterfall ပြဿနာတွေအတွက် data library ဒါမှမဟုတ် framework loader ကို သုံးပါ
- use(promise) က render တိုင်း မဖန်တီးထားတဲ့ promise ကိုသာ ဖတ်သင့်ပါတယ်
React Documentation — React