What is React Suspense?
React’s Suspense component was first added to React in v16.6, which was released in 2018. Suspense handles asynchronous operations like code splitting and data fetching. In simple terms, it lets you display a fallback component until the child component is fully loaded. The code below shows React Suspense’s syntax:
<Suspense fallback={<Loading />}>
<SomeComponent />
</Suspense>
Suspense in NextJS
Next.js supports server-side rendering, so the UI will take some time to load. In such cases, you can use Suspense to load the UI. The component in loading.js is defined as a functional component that can be exported as the default. The syntax is below:
export default function Loading() {
// You can add any UI inside Loading, including a Skeleton.
return <LoadingSkeleton />
}
Setting up our Next.js project
npx create-next-app@latest
After successfully creating of next project follow the below steps.
- Removing unnecessary files and folders.
- Creating
Loading.js
into the root. - Fetching posts from
[Jsonplaceholder](https://jsonplaceholder.typicode.com/)
. - Creating a
Posts route
into the app folder.
async function getPosts() {
await new Promise((resolve) => setTimeout(resolve, 2000));
let res = await fetch(
`https://jsonplaceholder.typicode.com/posts`
);
return res.json();
}
async function SocialPosts() {
let posts = await getPosts();
return (
<div>
<h3>Posts</h3>
{posts &&
posts.map((index) => {
return <li>{index.title}</li>;
})}
</div>
);
}
export default SocialPosts;
Here is the output:
Conclusion
Building a loading component with Next.js and React Suspense can significantly improve the user experience of your web application. With Suspense, you can easily create loading states for data-fetching and dynamic imports, making your application more responsive and efficient.
Top comments (0)