#Suspense
1 messages · Page 1 of 1 (latest)
Yes, you can use Suspense not only in pages but also in your own UI components. Suspense is a React feature that allows you to wrap a component that performs an asynchronous action, showing a fallback UI while it's happening, and then swapping in your component once the action completes.
For example, you can use Suspense in a component that fetches data, and show a loading message until the data is fetched. Here's an example:
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 fallback UI specified in the fallback prop of the Suspense component is shown.
You can also use Suspense with the useSearchParams function. If a route is statically rendered, calling useSearchParams() will cause the tree up to the closest Suspense boundary to be client-side rendered. This allows a part of the page to be statically rendered while the dynamic part that uses searchParams is client-side rendered. Here's an example:
import { Suspense } from 'react'
import SearchBar from './search-bar'
function SearchBarFallback() {
return <>placeholder</>
}
export default function Page() {
return (
<>
<nav>
<Suspense fallback={<SearchBarFallback />}>
<SearchBar />
</Suspense>
</nav>
<h1>Dashboard</h1>
</>
)
}
In this example, SearchBar is a component that uses searchParams. While the search parameters are being fetched, the SearchBarFallback component specified in the fallback prop of the Suspense component is shown.