code snippets

Streaming Parts of a Web Page (Suspense) Part 1

Next.js has quickly matured into a full stack solution and one of the tools in its arsenal is streaming content. Specifically you can plan to serve the slower-loading parts of a requested web page using a placeholder (fallback) that gets displayed while your slow (blocking) background process completes (think "slow returning API request from a busy NHL server during hockey playoffs" or "giant database query that takes forever to return"....)


1import { Suspense } from 'react'
2import { PostFeed, Weather } from './Components'
3 
4export default function Posts() {
5  return (
6    <section>
7      <Suspense fallback={<p>Loading feed...</p>}>
8        <PostFeed />
9      </Suspense>
10      <Suspense fallback={<p>Loading weather...</p>}>
11        <Weather />
12      </Suspense>
13    </section>
14  )
15}

Summary: The PostFeed and Weather components represent slow-to-return data feeds. Normally these async operations would prevent the rest of the page's content from displaying until the entire recordset is returned from the call(s) - PostFeed and Weather. The above code lets the page continue to load but instead of being blocked, the messages "Loading feed...." and "Loading weather...." are displayed in the short duration until the requested data is returned and displayed (like a placeholder).