DEV Community

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

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 />
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](
  4. Creating a Posts route into the app folder.
async function getPosts() {
  await new Promise((resolve) => setTimeout(resolve, 2000));
  let res = await fetch(

  return res.json();

async function SocialPosts() {
  let posts = await getPosts();
  return (
      {posts && => {
          return <li>{index.title}</li>;
export default SocialPosts;
Enter fullscreen mode Exit fullscreen mode

Here is the output:

Image description

Image description

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)