[ReactDoc] Suspense and Lazy
透過 Suspense 可以讓元件在 render 前先「等待」。自 React 18 起,Suspense 除了搭配 React.lazy 來做 dynamic loading 元件外,也支援搭配資料取得框架(如 Next.js、Relay)與 Server Components 使用。在 React 19 中,更可透過 use() Hook 搭配 Suspense 進行資料載入。
透過 dynamic imports 來達到 code-splitting 效果的方式可以參考 Code Splitting and Dynamic Imports。
官方提到的 Best Practice 是:
- 如果只是想做到 Code Splitting 的效果,只需使用
React.lazy - 如果要 dynamic loading 且在該元件未 render 完成前出現 loading 的提示(loading indicator)則使用:
React.Suspense
React.lazy:作為 code splitting 使用
React.lazy @ React Top-Level API
透過 React.lazy() 讓你可以動態地載入一個元件,並且達到 code splitting 的效果,如此避免使用者下載那些可能用不到的元件,以減少第一次載入頁面是所需的 bundle size。
const SomeComponent = React.lazy(() => import('./SomeComponent'));
接著在要使用這個元件的地方,要用 <Suspense /> 把這個需要動態載入 的元件包起來。
React.Suspense:想要看到 loading indicator 時
React.Suspense @ React Top-Level API
透過 <Suspense /> 可以在元件還沒有 render 完成前顯示載入的效果(loading indicator)。自 React 18 起,Suspense 除了搭配 React.lazy 載入動態元件外,也支援搭配資料取得框架和 Server Components 使用。
// https://legacy.reactjs.org/docs/react-api.html#reactsuspense
import { lazy, Suspense } from 'react';
import Spinner from './Spinner';
// code-splitting
const OtherComponent = lazy(() => import('./SomeComponent'));
const MyComponent = () => {
return (
<Suspense fallback={<Spinner />}>
<div>
<OtherComponent />
</div>
</Suspense>
)
}