Reputation: 3712
I have a Layout component that looks like this:
export const Layout = (props) => {
return (
<div>
<MenuBar />
{props.children}
<Footer />
</div>
);
};
...and I want to use this Layout component to render content for different pages like so:
export const App = () => {
return (
<div>
<Router>
<Layout>
<Switch>
<Route exact path="/">
<PageHome />
</Route>
<Route path="/about">
<PageAbout />
</Route>
</Switch>
<Layout />
</Router>
</div>
);
};
Now the problem I have is that each time the route changes, the props.children value changes and so the whole Layout component (including the MenuBar and Footer) get re-rendered as well as the page content. So my questions are:
Upvotes: 3
Views: 1937
Reputation: 28654
The Layout
itself must be re rendered, because it has new children, however you can prevent MenuBar
and Footer
components from re rendering by creating them using React.memo:
const MenuBar = React.memo(function MyComponent(props) {
/* render using props, it won't re rerender unless props change */
});
Upvotes: 6