Home > Blockchain >  Next js how to avoid re-rendering of common components between routed pages?
Next js how to avoid re-rendering of common components between routed pages?

Time:12-31

I have set up the basic router in Next js and I want multiple pages to share a component e.g. a header. The shared component is reloading on each new page load. (How) can I reuse components without rerendering them needlessly between page loads? This is really inefficient compared to CRA react-router nested routing removing the requirement for any form of shared components.

Sandox here

Shared component code as follows:

import React, { memo } from "react";

export default function hello() {}

export const Header = memo(() => {
  return (
    <>
      <h1>Next js Shared component</h1>
      <p>{Math.random()}</p>
    </>
  );
});

I have tried wrapping a common component in a memo to try to avoid rerender but that doesn't work. Is there a way to share components between pages in Next JS?

CodePudding user response:

You can place your shared components like Header inside _app.js, and remove from other components, like below:

// /pages/_app_.js
import React from "react";
import { Wrapper, Header } from "../common";

const MyApp = ({ Component, pageProps }) => {
  return (
    <>
      <Wrapper>
        <Header/>
        <Component {...pageProps} />
      </Wrapper>
    </>
  );
};

export default MyApp;
  • Related