「基礎から学ぶ Next.js」の感想・備忘録

スポンサーリンク

点数

86点

感想

第1章のJavaScript、TypeScript、React、Next.jsの解説がとてもわかりやすかった。

第2章と第4章のハンズオンはそれぞれNotion APIとUnsplash APIを利用しており、同じAPIを使わない限りはあくまで参考になる程度という感じだった。

第3章ではReact18とNext.js13の新機能について書かれいたが、現時点ではまだ時期尚早だと思う。
ただし、App Routerやサーバコンポーネントは今後必要になってくるかもしれないので、いい勉強になった。

基礎

環境構築

  1. npx create-next-app@latest nextjs-sample
  2. cd nextjs-sample
  3. npm run dev
    SSGは本来はビルド時に生成される(getStaticPropsが実行される)が、開発サーバの場合はページ読み込みごとに実行される(getServerSidePropsと同じ挙動)

ビルド

  1. npm run buildでビルド
  2. npm run startでビルド結果を実行(本番環境で使う)

SSRとSSG

  • SSG:ビルド時にサーバでHTMLを生成
  • SSR:リクエスト時にサーバでHTMLを生成
  • CSR:ブラウザ上で動的にHTMLを生成

SSR

import {GetServerSideProps, NextPage} from "next";

type Props = {
  msg: String
}
export const getServerSideProps: GetServerSideProps<Props>=async() => {
  return {
    props: {
      msg: 'hoge'
    }
  }
}
const Home2: NextPage<Props> = ({msg}) => {
  return (
    <main>
      <h1>{msg}</h1>
    </main>
  )
}
export default Home2

SSG

import {GetStaticProps, NextPage} from "next";

type Props = {
  msg: String
}
export const getStaticProps: GetStaticProps<Props>=async() => {
  return {
    props: {
      msg: 'hogehoge'
    }
  }
}
const Home3: NextPage<Props> = ({msg}) => {
  return (
    <main>
      <h1>{msg}</h1>
    </main>
  )
}
export default Home3

next/linkモジュール

import Link from "next/link";
//〜省略〜
<Link href="/index2">index2</Link>

ミドルウェア

  • プロジェクトルート(srcディレクトリを使っている場合はsrc内)のmiddleware.tsでmiddlrare関数を定義してエクスポートすると、リクエストの前後に任意の処理を挟むことができる。
  • configオブジェクトのmatcherで対象パスを指定可能。
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'

export function middleware(request: NextRequest) {
  return NextResponse.redirect(new URL('/index3', request.url))
}
export const config = {
  matcher: '/hoge(.*)',
}

コンポーネントの切り出し

  • 各ページで共通のHTMLはコンポーネントとして切り出すべき。
import {ReactNode} from "react";

type Props = {
  children: ReactNode
}
const Layout = ({children}: Props) => {
  return (
    <div style={{border: "1px solid #ccc"}}>{children}</div>
  )
}
export default Layout
import Layout from "../components/layout"

const Home = () => {
  return (
    <>
      <Layout>
        <main>
          <h1>TOP</h1>
        </main>
      </Layout>
    </>
  )
}
export default Home

Next.js 13

App Router

  • 2022年10月にリリースされたNext.js13からApp Routerが使えるようになった。
  • 従来にPages Routerではpagesディレクトリのコードを配置したが、App Routerはappディレクトリにコードを配置する。
  • App RouterではディレクトリがURLに対応する。
    app/dashbord/page.tsxは/dashbordでアクセス可能となる。
  • ディレクトリとURLが対応しているので、CSSやテストコードをディレクトリに格納することができるようになった。
  • App Routerのコンポーネントはデフォルトでサーバコンポーネントとして処理される。
  • サーバコンポーネントはReact18の新機能で、コンポーネント単位でSSRを行う仕組みである。
  • 従来のコンポーネント(クライアントコンポーネント)として動作させるには、コンポーネントファイルの先頭に'use client'を記述する。

コメント