nextjs layout rerendering
I have this code in _app.tsx (image). As you can see, anything that matches the /projects/.* regex has a ProjectSidebar Layout. My understanding was that this Layout gets rendered once. and whatever "children" gets passed down will be replaced. However, I put a console.log statement in ProjectSidebar, and it's getting logged when I click on different Links that bring me to the component that uses ProjectSidebar.
1. Why is that happening?
2. Even clicking on the same Link triggers the console.log statement. Why?
2 Replies
Would super recommend you check out the react dev tools because the profiler gives a pretty good picture of what's going on.
https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi?hl=en
I set up a fresh project wrapping Component in a layout (first image), that had Links to '/' and to another page called 'new' (second image). Then I ran the dev tools profiler and navigated from / to /new using the the Link in my Layout to see what would render and why. (third image), you can see that App rendered because both pageProps and Component updated and (fourth image) that Layout rendered because its props (Component) changed. Also want to note that like you said, clicking on a same link causes pageProps to update and App, Layout, and Component all render as a result.
I think the next docs really only point out that the Layout pattern is good for having the component show up on every page and having the component preserve its state across pages.
Last, just want to point out that if you go to nextjs.org and turn on "Highlight updates when components render." in devtools, you will see the same deal happening where clicking the home link triggers every component to render so I'm pretty sure this is expected.
React Developer Tools
Adds React debugging tools to the Chrome Developer Tools.
Created from revision 28ce1c171 on 3/22/2023.
Wow, thank you so much for this! So the behaviour is expected? That's unfortunate