Suspense
Normally with Serverside rendering (SSR). The following steps will be executed:
- On the server, fetch data for the entire app.
- Then, on the server, render the entire app to HTML and send it in the response.
- Then, on the client, load the JavaScript code for the entire app.
- Then, on the client, connect the JavaScript logic to the server-generated HTML for the entire app (this is hydration).
However, each step needs to finish before the next step could start, therefore creats delay.
<Suspense>
especially in React 18 can break down your app into smaller independent unit. Therefor, each <Suspense>
go through these steps independently and don't block the rest of the app.
This means that you can just use React.lazy()
for code splitting.
import React, { lazy, Suspense } from 'react';
const MyComponent = lazy(() => import('./MyComponent'));
function App() {
return (
<div>
<Suspense fallback={<div>Loading...</div>}>
<MyComponent />
</Suspense>
</div>
);
}
export default App;