Layouts

    The React model allows us to deconstruct a into a series of components. Many of these components are often reused between pages. For example, you might have the same navigation bar and footer on every page.

    If you only have one layout for your entire application, you can create a Custom App and wrap your application with the layout. Since the component is re-used when changing pages, its component state will be preserved (e.g. input values).

    1. // pages/_app.js
    2. import Layout from '../components/layout'
    3. export default function MyApp({ Component, pageProps }) {
    4. return (
    5. <Layout>
    6. <Component {...pageProps} />
    7. )
    8. }
    1. // pages/_app.js
    2. // Use the layout defined at the page level, if available
    3. const getLayout = Component.getLayout || ((page) => page)
    4. return getLayout(<Component {...pageProps} />)
    5. }

    When navigating between pages, we want to persist page state (input values, scroll position, etc.) for a Single-Page Application (SPA) experience.

    This layout pattern enables state persistence because the React component tree is maintained between page transitions. With the component tree, React can understand which elements have changed to preserve state.

    Note: This process is called reconciliation, which is how React understands which elements have changed.

    1. // pages/_app.tsx
    2. import type { ReactElement, ReactNode } from 'react'
    3. import type { NextPage } from 'next'
    4. getLayout?: (page: ReactElement) => ReactNode
    5. }
    6. type AppPropsWithLayout = AppProps & {
    7. Component: NextPageWithLayout
    8. }
    9. export default function MyApp({ Component, pageProps }: AppPropsWithLayout) {
    10. // Use the layout defined at the page level, if available
    11. const getLayout = Component.getLayout ?? ((page) => page)
    12. return getLayout(<Component {...pageProps} />)

    Inside your layout, you can fetch data on the client-side using useEffect or a library like . Because this file is not a Page, you cannot use or getServerSideProps currently.

    For more information on what to do next, we recommend the following sections: