Suspense with Server Components in Next.js
In next.js, we can create a special file called loading.js (or .jsx) for specific route or in root level that automatically wraps page.jsx and other nested routes. We can have small components like spinner, skeleton that are pre-rendered and can be instantly shown while page is loading data. We can define define laoding.jsx in for every route. We can even change the behaviour by defining our own suspense.
import { Suspense } from 'react'
import { Posts } from './Components'
export default function Posts() {
return (
<main>
<Navbar />
<Suspense fallback={<p>Loading posts...</p>}>
<Posts />
</Suspense>
<Footer />
</main>
)
}
In the above code, <Posts/> component is wrapped in suspense. <Navbar /> and <Footer /> typically do not require data fetching, so they can be instantly displayed. By wrapping <Posts /> in our custom suspense boundary, <Navbar /> and <Footer /> will instantly appear for the user.
How does Suspense help in Handling Asynchronous Operations in React ?
Suspense, first introduced in React 16, is a feature that aims to enhance the user experience by managing asynchronous operations. It simply lets you render a fallback UI decoratively while the child component is waiting for any asynchronous task to be completed.
Table of Content
- What is React Suspense?
- Project Initialisation
- Traditional Data Fetching Techniques
- How Suspense works?
- Use cases of React Suspense
- Suspense with Server Components in Next.js
- Conclusion