2021-02-26

Reactではなく、Next.jsにした理由

ReactからReact-staticになって、最終的にNext.jsになった話

post image

Reactに比べて良いところ

基本的にはReactと書き方は大体一緒だが、比較してよくなってる部分もある。 Built-In CSS Support や、Internationalized RoutingなどReactにはない特色もあるが、今回は特に気に入った何個かだけ紹介する。

Next.js公式ページ

File-system Routing

例えば、以下のようなpathでroutingするとしたら、

/
/about
/posts
/posts/[slug]

[slug] は記事のIDで、動的に変わるもの。

Reactの書き方

React Router を使って書いてみた。

import { BrowserRouter, Switch, Route } from 'react-router-dom';

function App() {
  return (
    <BrowserRouter>
      <Switch>
        <Route path="/" exact children={<Index />} />
        <Route path="/about" children={<About />} />
        <Route path="/posts" children={<Posts />} />
        <Route path="/posts/:slug" children={<Post />} />
      </Switch>
    </BrowserRouter>
  );
}

Componentの中にRoutingのパスなどの設定を書く事になる。 個人的にこの書き方もわかりやすくて嫌いではないが、Routingの処理はComponentとして書くべきなのか?という疑問は少しあった。

Next.jsの書き方

NextではFile-treeでRoutingができる。 上記と同じRoutingをしてみると、

src
 |-- pages
     |-- posts
     |    |-- [slug].tsx
     |    |-- index.tsx
     |-- about.tsx
     |-- index.tsx
     |-- _app.tsx
     |-- _document.tsx

Next.js 9.1以降ではsrcディレクトリがサポートされるのでpagesもsrcの下においている。 パスを特に書く必要なく、ファイルを置くだけで書ける。 個々のファイルがパスを意味して、各パスのTop-level Componentとして使える。

Linking to dynamic paths

[slug].tsx などの動的なパスにアクセスする時に、Linkする方法。

import Link from 'next/link'

function Posts({ posts }) {
  return (
    <ul>
      {posts.map((post) => (
        <li key={post.id}>
          <Link href="/posts/[slug]" as={`/posts/${post.slug}`}>
            <a>{post.title}</a>
          </Link>
        </li>
      ))}
    </ul>
  )
}

export default Posts

Pre Renderingが簡単

Next.jsは SSR,SSG の両方が簡単にできる。 Reactではそもそも SSG を試したことすらないのでどれほど簡単にできるかわからないが、Next.jsでは特にそれほどの設定は必要なく、すぐにできる。

❯ yarn run next build
❯ yarn run next export

これでoutというディレクトリに色々生成されるのでoutディレクトリをホスティングサーバーに置くだけでStaticなアプリケーションができる。 SSR, SSGやClient-side-renderingについてはまたいつか。

まとめ

Reactと比べてNext.jsで特に気に入った機能を何個か載せてみた。 Gatsby.jsはまだ試してみてないのでどっちが使いやすいのかまではわからないが、Next.jsを触ってみた感じ別にGatsby.jsを使わないといけない理由はまだない。 Next.jsと言っても基本は React + SSGジェネレーター のような物なのでReact好きの人は試してみてもすぐに書けると思う。