# 初探Suspense [Suspense doc](https://zh-hant.reactjs.org/docs/concurrent-mode-suspense.html) [codesandbox 官方範例](https://codesandbox.io/s/frosty-hermann-bztrp?file=/src/fakeApi.js:494-625) ```typescript= <Suspense fallback={'loading...'}> <SomeComponent /> </Suspense> ``` (一開始就fetch資料!) fetch data -> pending狀態 -> 組件被suspended -> Suspense看到底下組件還沒好,調用fallback的組件 -> 等組件的promise完成後 -> 渲染組件 ### 以往做法 以往的把fetch放在useState用的是fetch on render,就是說你render後才觸發fetch,舊方法除了比較沒效率之外,會導致所謂的race condition,各組件會互相競爭,例如我A組件明明還沒抓到資料,你B子組件怎麼在跑了,而我setState才剛完成你就要更新,很容易造成組件的waterfall 更新問題 !! 諸如此類的狀況。 像是這個範例 https://codesandbox.io/s/trusting-clarke-8twuq ,一旦你改變API的fetch timeout時間,有時候資料會"倒退",不會隨id改變而改變。 ### render as you fetch Suspense是採用render as you fetch的方法,組件會被 ```typescript= <Suspense fallback={'loading...'}>...</Suspense> ``` 包住,並且"馬上"渲染loading,fetch資料(不用等useEffect),也會先被啟用。 接著如果組件本身的資料還沒被fetch好,他會被"ZA WORLD"般的被停住,由Suspense 渲染 fallback中的組件。 
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up