Next.jsEasy
What is the _app.js file and what is it used for?
pages/_app.js (or _app.tsx) is the Pages Router component that wraps every page. Use it for global CSS, context providers, persistent layouts and per-page layout patterns. The App Router replaces it with the root app/layout.tsx.
What it does
Next.js renders _app with two props: Component (the active page) and pageProps (data from getStaticProps/getServerSideProps). Whatever you wrap around <Component {...pageProps} /> applies to every page.
Common uses
- Global CSS. In the Pages Router, global stylesheets can only be imported in
_app. - Providers. Theme, auth session, React Query or Redux providers.
- Persistent layout. UI that should not remount between page changes.
- Per-page layouts. A
getLayoutfunction on each page lets pages opt into different layouts. - Analytics or
reportWebVitals.
What to avoid
- Adding
getInitialPropsto_appdisables Automatic Static Optimization for every page, so all pages become server-rendered. - Fetching data here for all pages; it runs on every navigation.
App Router equivalent
app/layout.tsxis the root layout and must render<html>and<body>.- Global CSS is imported there.
- Providers go in a small Client Component (for example
app/providers.tsx) rendered by the layout. - Nested
layout.tsxfiles replace thegetLayoutpattern.
Code example
tsx
1// pages/_app.tsx2import "@/styles/globals.css";3import type { AppProps } from "next/app";4import type { NextPage } from "next";5import type { ReactElement, ReactNode } from "react";6import { ThemeProvider } from "@/components/theme";78export type NextPageWithLayout = NextPage & {9 getLayout?: (page: ReactElement) => ReactNode;10};1112type Props = AppProps & { Component: NextPageWithLayout };1314export default function MyApp({ Component, pageProps }: Props) {15 // Each page can choose its own layout; default is no extra wrapper16 const getLayout = Component.getLayout ?? ((page) => page);1718 return <ThemeProvider>{getLayout(<Component {...pageProps} />)}</ThemeProvider>;19}2021// App Router equivalent: app/layout.tsx22// export default function RootLayout({ children }: { children: React.ReactNode }) {23// return <html lang="en"><body><Providers>{children}</Providers></body></html>;24// }
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.