Skeleton Loading with Suspense in Next.js 13

34 min read

In Next.js 13, you can use the Skeleton component with Suspense to show a skeleton loading animation while data is being fetched or components are being dynamically loaded. Here's how you can implement it:

  1. First, make sure you have Next.js 13 installed in your project.

  2. Import the required components from the next package:

import { Suspense } from 'react';
import { Skeleton } from 'next';
  1. Wrap your component or data fetching logic in the Suspense component:
<Suspense fallback={<Skeleton />}>
  {/* Your component or data fetching logic */}
</Suspense>
  1. Inside the fallback prop of the Suspense component, you can add a Skeleton component or any other loading animation or placeholder you want to show while the component or data is being loaded.

Here's a complete example that demonstrates the usage of Skeleton with Suspense in Next.js 13:

import { Suspense } from 'react';
import { Skeleton } from 'next';

const MyComponent = () => {
  // Simulating a data fetching delay
  const data = fetchDataSlowly();

  return <h1>{data}</h1>;
};

const fetchDataSlowly = () => {
  // Simulating a delay of 2 seconds
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve('Data fetched!');
    }, 2000);
  });
};

const MyPage = () => {
  return (
    <div>
      <h1>My Page</h1>

      <Suspense fallback={<Skeleton />}>
        <MyComponent />
      </Suspense>
    </div>
  );
};

export default MyPage;

In this example, the MyComponent component simulates data fetching with a delay of 2 seconds. While the data is being fetched, the fallback prop of Suspense is triggered, and the Skeleton component is rendered. Once the data is fetched, the actual component content is displayed.

Note that this example uses the Skeleton component provided by Next.js. However, you can also use any other loading animation or placeholder component as your fallback in the Suspense component.