Next.js remounts root layout.tsx when navigating through pages

18 Views Asked by At

I have project that uses next.js 14. I'm using the default app navigation system. So, as required I have a root layout.tsx, which, from my understanding, should mount only once at the beginning of the process. However, state kept going back to its default value (first using redux, then react context, and now even zustand) when I navigated to any new route.

I believe the problem is caused by everything, including layout.tsx, being re-mounted each time I navigate to a different route. To test this I added a console.log to my layout.tsx function. Indeed, each time I navigate to a new route, the console.log is triggered.

Here's my layout.tsx:

import type { Metadata } from "next";
import "./globals.css";
import Header from "./components/Header/Header";
import Footer from "./components/Footer/Footer";


export const metadata: Metadata = {
  title: "title",
  description: "description",
};

export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  console.log("mounting layout")
  return (
    <html lang="en">
      <body>
        <Header />
        {children}
        <Footer />
      </body>
    </html>
  );
}

Also, here's a photo of my project structureenter image description here

I expected the state (redux, context, zustand) to persist through navigation. I tried different tools to manage state. I also looked into next.js documentation and everything points out that layout.tsx should not remount on route navigation.

0

There are 0 best solutions below