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!