ProNextJS
    Professional Next.js Course
    Loading price
    30-Day Money-Back Guarantee
    lesson

    Adding Suspense to the Application

    Jack HerringtonJack Herrington

    Inside of the stocks-with-suspense directory of the repo, you'll find the code for adding Suspense.

    Let's start by adding Suspense to our main page component. We can do this by importing Suspense from React and wrapping our dashboard component with it. We'll also add a fallback prop to display a loading message while the data is being fetched:

    // inside src/app/page.tsx
    
    import { Suspense } from "react";
    import Dashboard from "./dashboard";
    
    export default async function Home() {
      return (
        <main className="text-2xl max-w-3xl mx-auto">
          <Suspense fallback={<div>Loading...</div>}>
            <Dashboard />
          </Suspense>
        </main>
      );
    }
    

    If we run our application now, you'll see a "Loading..." message momentarily before the dashboard appears with the stock data. This is great, but we can do better!

    Challenge

    Currently, our getStocks function fetches all the stock data concurrently and waits for all of it to be resolved before rendering the dashboard. However, since the delay for each stock is random, we could fetch and render them individually. This would give the user a more granular loading experience.

    Your challenge is to find a way to achieve this using React's useHook to manage the state of each stock individually. This approach will allow us to render each stock component as soon as its data becomes available, providing a smoother and more responsive user experience.

    In the next video, we'll walk through my approach to implement this using Suspense and a custom hook!

    Transcript

    Okay, I've copied the code into another directory called stocks with suspense. Obviously that's available to you in the github repo Let me go and add a suspense first to the page to see if that helps so bring in suspense from react and I'll just wrap the dashboard in the suspense and give it a fallback to say loading. Let's try it out and see how that works. So now I get loading and then I get the data. All right, not bad and everything still works.

    We've got our client components going, so that's good. But when we think about it, if we look back over at our get stocks code, we can see that the delay for any specific stock is random. So we could Actually, instead of waiting for them all to resolve, we could go and individually await each one. What do you think about that? So can you think of a way to granularize this such that each one of these stocks comes in individually, again, using suspense?

    Now a hint, you might want to use the use hook in this example. So I'll leave that to you and I'll show you in the next video how I've done it.