next.jscomponentslazy-loadingnext.js14

In Next.js 14 can a component be pre-loaded or set with priority?


Building my first Next.js 14 site I'm looking to learn how I can better implement site performance. In my layout.tsx I have a header component

layout.tsx (stripped down example)

import '@/styles/globals.css'

import Header from 'Header'
import Footer from 'Footer'

export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode
}>) {
  return (
    <html lang="en">
      <body>
        <div className="flex flex-col h-screen">
          <Header /> // priority here?
          <main className="grow"> // lazy load everything below?
            {children}
          </main>
          <Footer />
        </div>
      </body>
    </html>
  )
}

and I was wondering similar to images with Priority is there a way to set priority for the entire Header component but everything else with the site be lazy loaded even if I'm building RSC?

Closest topic on this I could find was: "Lazy Load React Server Components"

Looked to see if this was available in the docs with no luck:

In Next.js 14 with app router is there an ability to set a priority on a component level and not just an image level that would allow everything below the above-the-fold to be lazy loaded?


Solution

  • After a further dive into Next.js documentation I was able to find Lazy Loading that talks about using dynamic imports with next/dynamic:

    next/dynamic is a composite of React.lazy() and Suspense. It behaves the same way in the app and pages directories to allow for incremental migration.

    So I can do:

    import dynamic from 'next/dynamic'
    
    import '@/styles/globals.css'
    
    import Header from 'Header'
    
    // dynamic here
    const Footer = dynamic(() => import('Footer'), {
      loading: () => <p>Loading...</p>,
    })
    
    export default function RootLayout({
      children,
    }: Readonly<{
      children: React.ReactNode
    }>) {
      return (
        <html lang="en">
          <body>
            <div className="flex flex-col h-screen">
              <Header /> 
              <main className="grow">
                {children}
              </main>
              <Footer />
            </div>
          </body>
        </html>
      )
    }