Home > AI > Frontend > Next.js >

Next.js loading

Loading is specified within loading.tsx located in the folder and utilized in page.tsx using Suspense. Below is an illustration for the /dashboard route.

To begin with, the folder structure appears as follows:

dashboard 
- loading.tsx
- page.tsx

page.tsx

import { Suspense } from 'react'
import ClientPage from '../client/page'
import ServerPage from '../server/page'
import DashboardLoading from './loading'

export default function DashboardPage() {
  return (
    <section>
      <Suspense fallback={<DashboardLoading />}>
        <ClientPage />
      </Suspense>
      <Suspense fallback={<p>Loading server ...</p>}>
        <ServerPage />
      </Suspense>
    </section>
  )
}

loading.tsx

export default function DashboardLoading() {
  return 'Loading Dashboard';
}

cleint/page.tsx

export default async function ClientPage() {
  console.log('client')

  await new Promise(resolve => setTimeout(resolve, 30000));

  return (
    <h1>Client Page</h1>
  )
}

server/page.tsx

export default function ServerPage() {
  console.log('server')

  return (
    <h1>Server Page</h1>
  )
}

Better utilize loading and Suspense in page.tsx. When navigating from /server to /client and back again, if client/page.tsx is still loading, the content from server/page.tsx remains visible, leading to potential confusion.

Leave a Reply