1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Next.jsの_app.tsxとは何か

1
Posted at

Next.js の _app.tsx とは何か

概要

_app.tsx は Next.js における全ページの親コンポーネントです。
どのURLにアクセスしても、必ずこのファイルが最初に呼び出されます。

コード全体

import "@/styles/globals.css";
import type { AppProps } from "next/app";

export default function App({ Component, pageProps }: AppProps) {
  return <Component {...pageProps} />;
}

各行の解説

グローバルCSSのインポート

import "@/styles/globals.css";
  • ここでインポートすることでアプリ全体のすべてのページに適用される
  • Next.js では、グローバル CSS は _app.tsx 以外でインポートするとエラーになる

型のインポート

import type { AppProps } from "next/app";
  • AppProps は Next.js が提供する TypeScript の型
  • import type は型情報だけをインポートする構文(実行時のバンドルに含まれない)

App コンポーネント本体

export default function App({ Component, pageProps }: AppProps) {
  return <Component {...pageProps} />;
}

AppProps が持つ2つのプロパティ

プロパティ 役割
Component 現在のページコンポーネント(URLに対応する pages/ 以下のファイル)
pageProps getStaticPropsgetServerSideProps から返ってきたデータ

なぜこれでページがレンダリングされるのか

ポイント:Component に何が入るかは Next.js が決める

Next.js はアクセスされた URL を見て、対応するページファイルを自動的に Component に代入してから App() を呼び出します。

/        → Component = pages/index.tsx
/about   → Component = pages/about.tsx
/contact → Component = pages/contact.tsx

<Component {...pageProps} /> の意味

Component にはReactコンポーネント(関数)が入っているので、JSXで <Component /> と書くとそのコンポーネントがレンダリングされます。

// たとえば /about にアクセスした場合、実質的にこれと同じ
return <About {...pageProps} />;

処理の流れ

ユーザーが /about にアクセス
  ↓
Next.js が Component = about.tsx を決定
  ↓
App({ Component, pageProps }) を呼び出す
  ↓
<Component {...pageProps} /> をレンダリング
  ↓
画面に /about のページが表示される

_app.tsx の代表的な使い方

今の状態は最小構成です。実際のプロジェクトでは以下のような処理を追加します。

export default function App({ Component, pageProps }: AppProps) {
  return (
    <AuthProvider>       {/* 認証状態をアプリ全体で共有 */}
      <ThemeProvider>    {/* テーマ(ダークモードなど) */}
        <Layout>         {/* 全ページ共通のナビバー・フッター */}
          <Component {...pageProps} />
        </Layout>
      </ThemeProvider>
    </AuthProvider>
  );
}
用途 概要
グローバルCSSの適用 全ページに共通のスタイルを当てる
共通レイアウト ナビバー・フッターなどを全ページに表示
Context Provider 認証状態・テーマなどをアプリ全体で共有
ページ遷移アニメーション ページが切り替わるときのアニメーション処理

まとめ

  • _app.tsx は全ページの共通処理を一箇所に書く場所
  • Component に何が入るかは Next.js フレームワーク側が自動で決める
  • _app.tsx 自身は「どう表示するか」だけを担当する設計
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?