1
votes

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:

  1. Can I prevent Layout re-rendering when the props.children value changes?
  2. If not, is the only way to prevent Layout from rerendering on each route change to move the Switch component out of the Layout's children?
1
How are you passing the props toi the Layout ? - Ali Al Amine
Every component has a props object passed into it. In this case, the props object has a non-falsey children property in virtue of its wrapping around the switch. - Magnus

1 Answers

5
votes

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 */
});