26
loading...
This website collects cookies to deliver better user experience
/components
folder) in two different pages (defined in /pages
) in Next.js, then the component will actually be re-rendered when you navigate from one page to the other.App
component./pages/_app.js
if it doesn't exist already, and add the components you want to persist in there.<Layout />
component between page changes:// pages/_app.js
import Layout from '../components/layout'
function MyApp({ Component, pageProps }) {
return (
// Add your header, footer, etc. in Layout and they will persist
<Layout>
// Don't change this. `Component` will be set to the current page component
<Component {...pageProps} />
</Layout>
)
}
export default MyApp
App
component? What's happening under the hood?<Foo />
to the page <Bar />
(defined in pages/foo.js
and pages/bar.js
respectively) by clicking a Next.js link. Here is what will happen:<Bar />
is fetched from the server, if it's not already prefetched; ReactDOM.render()
with 2 arguments: the first one is the new React element to render (it can be roughly thought of as the updated App
component), and the second one is the DOM container element (it's always <div id="__next"></div>
) that the new React element is rendered into.App
component into the <div id="__next"></div>
DOM container element. React will then take care of diffing the new and old React elements and decide which part of the DOM to re-render and which part to update.App
component looks like this:import '../styles/globals.css'
function MyApp({ Component, pageProps }) {
// Component will be set to the current page component
return <Component {...pageProps} />
}
export default MyApp
Component
variable will be set to the current page component. This means the old React element will look like this:<Foo {...pageProps} />
<Bar {...pageProps} />
<Foo />
and <Bar />
are two different components and are considered as of different types, so the part of the DOM that corresponds to <Foo />
will be destroyed and re-rendered as <Bar />
.App
component approach works. If you're using the suggested custom App
component above, then the old React element will look like this:<Layout>
<Foo {...pageProps} />
</Layout>
<Layout>
<Bar {...pageProps} />
</Layout>
<Foo />
is still going to be destroyed and re-rendered as <Bar />
, but <Layout />
will persist.