#Can I use Suspense for a component inside layout

1 messages · Page 1 of 1 (latest)

tight vault
#

Can Suspense be used to render a skeleton for a component used in the layout?

kind prairieBOT
#

Hi @tight vault. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Yes, you can use Suspense to render a skeleton for a component used in the layout. The Suspense component works by wrapping a component that performs an asynchronous action, such as fetching data. It shows a fallback UI (like a skeleton or spinner) while the data is being fetched, and then swaps in your component once the action completes.

Here's an example from the Next.js documentation (https://nextjs.org/docs/app/building-your-application/routing/loading-ui-and-streaming):

import { Suspense } from 'react'
import { PostFeed, Weather } from './Components'
 
export default function Posts() {
 return (
 <section>
 <Suspense fallback={<p>Loading feed...</p>}>
 <PostFeed />
 </Suspense>
 <Suspense fallback={<p>Loading weather...</p>}>
 <Weather />
 </Suspense>
 </section>
 )
}

In this example, PostFeed and Weather are components that fetch data. While the data is being fetched, the text "Loading feed..." or "Loading weather..." is displayed. Once the data has been fetched, the PostFeed and Weather components are rendered.

You can use this pattern for any component that fetches data, including components used in the layout. However, be aware that there are some open issues (https://github.com/vercel/next.js/issues/51581) with using Suspense in Next.js, particularly in production builds.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: