DEV Community

Cover image for How to create suspense in the next JS?
ZeeshanMustfai
ZeeshanMustfai

Posted on

How to create suspense in the next JS?

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>
Enter fullscreen mode Exit fullscreen mode

Suspense in NextJS

Image description

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 />
}
Enter fullscreen mode Exit fullscreen mode

Setting up our Next.js project

npx create-next-app@latest
Enter fullscreen mode Exit fullscreen mode

After successfully creating of next project follow the below steps.

  1. Removing unnecessary files and folders.
  2. Creating Loading.js into the root.
  3. Fetching posts from [Jsonplaceholder](https://jsonplaceholder.typicode.com/).
  4. 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;
Enter fullscreen mode Exit fullscreen mode

Here is the output:

Image description

Image description

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)