Context
I use a nested routes/layout setup in react-router
(v6.8).
const router = createBrowserRouter(
createRoutesFromElements(
<Route path="/" element={<BasicLayout />}>
<Route path="demo" element={<BasicNestedLayout />}>
<Route path="index" element={<Index />} />
<Route path="about" element={<About />} />
<Route path="topics" element={<Topics />} />
</Route>
</Route>
)
);
The user can click Link
components on BasicNestedLayout
to switch between the three sub routes (index
, about
and topic
).
Here is a reproducible example: app | stackblitz editor
Problem
When monitoring the app with React Chrome DevTools, it looks like everything on the page does rerender when I click on a Link
. This includes BasicLayout
, which contains just the App Header
and is the parent of BasicNestedLayout
where the Link
and its dependent content lives. All components are highlighted (devtools option = Highlight updates when components render).
A quick search on StackOverflow reveals that this was already a challenge in react-router
v4/5, but the accepted answers suggest to switch route props from component=
to render=
, which have both been replaced by element=
in v6 (doc).
How can one prevent the rerender of BasicLayout
when nothing has changed apart from its children?
Alternatively, is it possible that the React Dev Tools is wrong? I noticed that the useEffect
hooks, written without dependencies to run at each rerender, don't seem to print their console.log()
in the Console more than once.