Nextjs 13.5.4: Parent loading page is overwriting child loading page

917 views Asked by At

I'm using nextjs 13.5.4 with app router. I'm trying to implement different loading.tsx for every page but problem is the parent loading.tsx style is always showing while rendering nested pages with it's own loading.tsx. so when i render a nested page there are multiple loading pages applying before the data been fetch.

2

There are 2 answers

3
Robin Thomas On

That's by design of Next.js.

  • Any route segment can optionally define its own Layout. These layouts will be shared across all pages in that segment.
  • Layouts in a route are nested by default. Each parent layout wraps child layouts below it using the React children prop.

https://nextjs.org/docs/app/building-your-application/routing/pages-and-layouts

So if you have a app/parent/layout.tsx and app/parent/child/layout.tsx:

  • When you visit /parent, only parent/layout.tsx will be applied
  • When you visit /parent/child, both layouts will be applied, with parent/child/layout.tsx wrapped by parent/layout.tsx

You can read more about this behaviour here: https://nextjs.org/docs/app/building-your-application/routing/pages-and-layouts#nesting-layouts

0
Oluwatowo Rosanwo On

I think a good solution is to remove the loading.tsx from the parent route, and then add a suspense with a loader as fallback, like so

function page() {
  return (
    <div>
      <h1>Welcome</h1>
     <Suspense fallback={<Loading />}>
       <Main />
     </Suspense>
   </div>
 );
}

Here, The main async part of the page (all your Nextjs data-fetching logic) can go into Main, Nextjs will stream the components in as soon as the data is available, With this, child routes will no longer have any loading.tsx to inherit from, and might as well use their own dedicated loading.tsx