vercel / next.js

The React Framework
https://nextjs.org
MIT License
122.63k stars 26.25k forks source link

Link triggers full root layout rerender in production build / static export #64882

Open jlhervy opened 2 months ago

jlhervy commented 2 months ago

Link to the code that reproduces this issue

https://github.com/jlhervy/test-app-nextjs/

To Reproduce

Start the application in development, clic the navigation buttons to the left, and notice that the root layout does not rerender. Now, produce a static export, or a production build, serve the static files (nginx, python -m http.server) or run next start, and clic the navigation buttons. This time, we can see that the root layout rerenders on each navigation (the console.log triggers), even though there is no state change.

In my real application, this is annoying since I have particles in the background that change layout at each navigation.

Current vs. Expected behavior

I expected the root layout to not rerender as it is in development.

Provide environment information

Operating System:
  Platform: win32
  Arch: x64
  Version: Windows 10 Enterprise
  Available memory (MB): 16065
  Available CPU cores: 8
Binaries:
  Node: 20.11.1
  npm: N/A
  Yarn: N/A
  pnpm: N/A
Relevant Packages:
  next: 14.2.2
  eslint-config-next: 14.2.2
  react: 18.2.0
  react-dom: 18.2.0
  typescript: 5.4.5
Next.js Config:
  output: export

Which area(s) are affected? (Select all that apply)

Not sure, Output (export/standalone)

Which stage(s) are affected? (Select all that apply)

next build (local), next start (local)

Additional context

I tried several things, multiple servers and Link configuration, server vs client components, but each time the root layout rerenders.

jlhervy commented 2 months ago

I would like to be a little more specific : Here is the root layout :

export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  console.log("RootLayout");
  return (
    <html lang="en" className="min-h-screen dark">
      <body className="flex flex-col mx-auto text-gray-100 pt-10 w-6/12">
      <SideBar />
        {children}</body>
    </html>
  );
}

Here is the Sidebar (part of it) :

const SideBar = () => {

  const pathname = usePathname();

  return (
    <div className=" ">
      <Sidebar aria-label="Sidebar with multi-level dropdown example" className="z-10 w-48 !opacity-80 !text-gray-100">
        <Sidebar.Items>
          <Sidebar.ItemGroup>
            <Sidebar.Item as={Link} href="/chatbot/" icon={HiBeaker} active={pathname == "/chatbot/"}>
              Chatbot
            </Sidebar.Item>
            <Sidebar.Item as={Link} href="/edit/" icon={HiCode} active={pathname == "/edit/"}>
              Éditeur SQL
            </Sidebar.Item>

When I click the sidebar's items, in dev mode, the console.log("RootLayout"); does not trigger. When I produce a static export, and click the same items, the console.log("RootLayout"); triggers at every page change.

raRaRa commented 2 months ago

Same issue here, adding 'use client' to the layout actually fixed it for me. Really odd issue. In my case I'm not doing static export, the site is hosted on Vercel and this only breaks on prod, while it works as expected on dev.

jlhervy commented 2 months ago

Same issue here, adding 'use client' to the layout actually fixed it for me. Really odd issue.

Yes, but I actually have "use client" in the layout : https://github.com/jlhervy/test-app-nextjs/blob/main/app/layout.tsx

And I still get the problem with static export

florian-lp commented 2 months ago

Possibly related to / duplicate of #52558.

jlhervy commented 2 months ago

Yes, after searching in the issues I noticed that the issue has come up several times. In one of the posts, someone posted a code that didn't use the Link component directly, but instead :

  const { push } = useRouter()
return (
      <Button onClick={() => push('/about')} className={pathname === '/about/' ? 'text-red-500' : ''}>home</Button>
      <Button onClick={() => push('/edit')} className={pathname === '/edit/' ? 'text-red-500' : ''}>info</Button>
)

And indeed, the root layout does not rerender with these buttons, compared with a Link.

However, it does not rerender only for very simple pages. For example with this page :

'use client'

import React from 'react';

export default function Tables() {
    return (
        <div className="flex flex-col">
            page TABLES
        </div>
    );
}

But if I only add this import to the top :

import { List } from "flowbite-react";

without even using it, then the root layout starts to re-render again...

florian-lp commented 2 months ago

When using a minimal reproduction (with 'use client' in the root layout) I actually did not observe a re-render most of the time. After repeated client-side navigations, it does appear to re-render every now and then, however, it does not re-mount. I'm not actually sure what the intended behavior surrounding this is.

For the time being, I suggest using either useEffect or splitting the code out into a separate client component.

jlhervy commented 2 months ago

Could you share your minimal reproduction please ? Does it use flowbite and Links ?

For me, the re-render is problematic because I have a background of particles, and the distribution is modified with every page change. Moreover, it is problematic because there is absolutely no re-render in dev mode (even after repeated client-side navigation), but it happens in production / static export.

florian-lp commented 2 months ago

My minimal reproduction omitted flowbite, however, I've just tested it with your repo as well and still observe the same behaviour as I mentioned before. This behaviour seems to be related to browser caching. When a new revalidation payload is fetched the root layout seems to re-render (which is indeed an issue).

Is there anything preventing you from using useEffect for your use case btw?

jlhervy commented 2 months ago

Ok I can notice the behaviour you mention, the re-loading doesn't trigger at every page change, but seem to come randomly.

In my real application, I use tsParticles and this code : https://github.com/tsparticles/react/#readme

I tried to add useEffect to several places in the Particles component, but did not succeed because the particlesLoaded function would still trigger.

Finally, I used React Memo this way in my layout :

const MemoizedParticles = React.memo(ParticlesCustom);
//...
<html lang="en" className="min-h-screen dark" >
      <body>
        <MemoizedParticles />

And now it works, it does not rerender with page changes. So for now I am satisfied with this workaround.

Thank you for your help.

florian-lp commented 2 months ago

Glad to hear you found a workaround for the time being.

I hope to look into this issue/the related ones more soon.