Data Streaming and Suspense in NextJS
What is Suspense ?
Suspense improves user experience by handle loading states in elegant manner. Suspense associates a fallback component with a Component being rendered. This fallback component displays loading state while component is loaded to client. Thus UI appears to be “doing something” until First Contentful Paint . For example if Component “RepoComponentLoading” is designed to display loading state while “RepoComponent” is loading, we can wrap RepoComponent inside Suspense as follows:
<Suspense fallback={<RepoComponentLoading />}>
<RepoComponent slug="django" />
</Suspense>
NextJS keep displaying RepoComponentLoading until RepoComponent is visible.
What is Streaming in NextJS ?
Instead of loading a large chunk representing multiple component being rendered at server, streaming breaks that one big chunk into multiple smaller chunks, each representing a different Server Side Component. These chunks are then loaded to Client one by one there by improving Core Vital Stats.
The diagram above clearly illustrates that Streaming is “Incremental” Server Side rendering to improve user-experience.
Let’s do some fireworks
Our page is rendering multiple components:
As shown in diagram below, Components are getting loaded in chunks one by one. When the same page is visited for next time, it is super-fast (Server Side components).
The Loading Component is:
And Main Component is (Detailed explanation here ):
You can download source code from this repo.
Happy Coding.