javascript / intermediate
Snippet
Prefetching External Data for Client Components
To avoid 'waterfalls' where client components wait to start fetching data until they are hydrated, you can initiate a promise in a Server Component and pass it as a prop. The Client Component can then use 'use()' to resolve it.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
// Server Componentexport default async function Page() {const dataPromise = fetchData(); // Start fetch earlyreturn (<main><h1>Dashboard</h1><Suspense fallback={<p>Loading...</p>}><ClientChart dataPromise={dataPromise} /></Suspense></main>);}
nextjs
Breakdown
1
const dataPromise = fetchData()
Initiates a fetch on the server immediately, without awaiting it here.
2
<ClientChart dataPromise={dataPromise} />
Passes the pending promise to a client component as a prop.
3
<Suspense fallback={...}>
Ensures the UI shows a fallback while the promise passed to the client is resolving.