Magnus
Magnus

Reputation: 3712

React Hooks: how to prevent re-rendering the whole component when only the props.children value changes?

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?

Upvotes: 3

Views: 1937

Answers (1)

Giorgi Moniava
Giorgi Moniava

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

Related Questions