コンテンツにスキップ

useRouter

アプリ内の任意の関数コンポーネント内でrouterオブジェクトにアクセスしたい場合は、useRouterフックを使用できます。以下の例をご覧ください。

import { useRouter } from 'next/router'
 
function ActiveLink({ children, href }) {
  const router = useRouter()
  const style = {
    marginRight: 10,
    color: router.asPath === href ? 'red' : 'black',
  }
 
  const handleClick = (e) => {
    e.preventDefault()
    router.push(href)
  }
 
  return (
    <a href={href} onClick={handleClick} style={style}>
      {children}
    </a>
  )
}
 
export default ActiveLink

useRouterReactフックであるため、クラスでは使用できません。withRouterを使用するか、クラスを関数コンポーネントでラップする必要があります。

routerオブジェクト

以下は、useRouterwithRouterの両方によって返されるrouterオブジェクトの定義です。

  • pathname: String - /pagesの後に続く現在のルートファイルのパス。したがって、basePathlocale、末尾のスラッシュ(trailingSlash: true)は含まれません。
  • query: Object - 動的ルートパラメータを含む、オブジェクトにパースされたクエリ文字列。ページがサーバーサイドレンダリングを使用しない場合、プリレンダリング中は空のオブジェクトになります。デフォルトは{}です。
  • asPath: String - ブラウザに表示されるパス。検索パラメータを含み、trailingSlash設定を尊重します。basePathlocaleは含まれません。
  • isFallback: boolean - 現在のページがフォールバックモードにあるかどうか。
  • basePath: String - アクティブなbasePath (有効な場合)。
  • locale: String - アクティブなロケール (有効な場合)。
  • locales: String[] - サポートされているすべてのロケール (有効な場合)。
  • defaultLocale: String - 現在のデフォルトロケール (有効な場合)。
  • domainLocales: Array<{domain, defaultLocale, locales}> - 設定されているドメインロケール。
  • isReady: boolean - ルーターフィールドがクライアントサイドで更新され、使用準備ができているかどうか。useEffectメソッド内でのみ使用し、サーバー上での条件付きレンダリングには使用しないでください。自動静的最適化ページのユースケースについては関連ドキュメントを参照してください。
  • isPreview: boolean - アプリケーションが現在プレビューモードにあるかどうか。

asPathフィールドを使用すると、ページがサーバーサイドレンダリングまたは自動静的最適化を使用してレンダリングされる場合に、クライアントとサーバーの間で不一致が発生する可能性があります。isReadyフィールドがtrueになるまでasPathの使用は避けてください。

以下のメソッドがrouterに含まれています。

router.push

クライアントサイドの遷移を処理します。このメソッドはnext/linkでは不十分な場合に役立ちます。

router.push(url, as, options)
  • url: UrlObject | String - ナビゲート先のURL(UrlObjectプロパティについてはNode.JS URLモジュールのドキュメントを参照)。
  • as: UrlObject | String - ブラウザのURLバーに表示されるパスのオプションのデコレーター。Next.js 9.5.3以前は、動的ルートに使用されていました。
  • options - 以下の設定オプションを持つオプションオブジェクト
    • scroll - オプションのブール値。ナビゲーション後にページ上部へスクロールするかどうかを制御します。デフォルトはtrueです。
    • shallow: getStaticPropsgetServerSideProps、またはgetInitialPropsを再実行せずに現在のページのパスを更新します。デフォルトはfalseです。
    • locale - オプションの文字列。新しいページのロケールを示します。

外部URLにrouter.pushを使用する必要はありません。window.locationの方がそのようなケースに適しています。

事前に定義されたルートであるpages/about.jsへのナビゲーション

import { useRouter } from 'next/router'
 
export default function Page() {
  const router = useRouter()
 
  return (
    <button type="button" onClick={() => router.push('/about')}>
      Click me
    </button>
  )
}

動的ルートであるpages/post/[pid].jsへのナビゲーション

import { useRouter } from 'next/router'
 
export default function Page() {
  const router = useRouter()
 
  return (
    <button type="button" onClick={() => router.push('/post/abc')}>
      Click me
    </button>
  )
}

認証の背後にあるページに役立つ、ユーザーをpages/login.jsにリダイレクトする

import { useEffect } from 'react'
import { useRouter } from 'next/router'
 
// Here you would fetch and return the user
const useUser = () => ({ user: null, loading: false })
 
export default function Page() {
  const { user, loading } = useUser()
  const router = useRouter()
 
  useEffect(() => {
    if (!(user || loading)) {
      router.push('/login')
    }
  }, [user, loading])
 
  return <p>Redirecting...</p>
}

ナビゲーション後の状態のリセット

Next.jsで同じページにナビゲートしても、Reactは親コンポーネントが変更されない限りアンマウントしないため、ページのステートはデフォルトでリセット**されません**。

pages/[slug].js
import Link from 'next/link'
import { useState } from 'react'
import { useRouter } from 'next/router'
 
export default function Page(props) {
  const router = useRouter()
  const [count, setCount] = useState(0)
  return (
    <div>
      <h1>Page: {router.query.slug}</h1>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increase count</button>
      <Link href="/one">one</Link> <Link href="/two">two</Link>
    </div>
  )
}

上記の例では、/one/twoの間を移動しても、カウントは**リセットされません**。トップレベルのReactコンポーネントであるPageが同じであるため、useStateはレンダリング間で維持されます。

この動作を望まない場合は、いくつかの選択肢があります。

  • useEffectを使用して各状態が更新されることを手動で確認します。上記の例では、次のようになります。

    useEffect(() => {
      setCount(0)
    }, [router.query.slug])
  • Reactのkeyを使用して、Reactにコンポーネントを再マウントするよう指示します。すべてのページでこれを行うには、カスタムアプリを使用できます。

    pages/_app.js
    import { useRouter } from 'next/router'
     
    export default function MyApp({ Component, pageProps }) {
      const router = useRouter()
      return <Component key={router.asPath} {...pageProps} />
    }

URLオブジェクトを使用

next/linkで使用できるのと同じようにURLオブジェクトを使用できます。urlasの両方のパラメータに機能します。

import { useRouter } from 'next/router'
 
export default function ReadMore({ post }) {
  const router = useRouter()
 
  return (
    <button
      type="button"
      onClick={() => {
        router.push({
          pathname: '/post/[pid]',
          query: { pid: post.id },
        })
      }}
    >
      Click here to read more
    </button>
  )
}

router.replace

next/linkreplaceプロップと同様に、router.replaceは新しいURLエントリがhistoryスタックに追加されるのを防ぎます。

router.replace(url, as, options)
  • router.replaceのAPIは、router.pushのAPIとまったく同じです。

次の例をご覧ください。

import { useRouter } from 'next/router'
 
export default function Page() {
  const router = useRouter()
 
  return (
    <button type="button" onClick={() => router.replace('/home')}>
      Click me
    </button>
  )
}

router.prefetch

より高速なクライアントサイド遷移のためにページをプリフェッチします。このメソッドは、next/linkを使用しないナビゲーションにのみ役立ちます。next/linkはページのプリフェッチを自動的に処理するためです。

これは本番環境のみの機能です。Next.jsは開発環境ではページをプリフェッチしません。

router.prefetch(url, as, options)
  • url - 明示的なルート (例: /dashboard) および動的ルート (例: /product/[id]) を含む、プリフェッチするURL
  • as - urlのオプションのデコレーター。Next.js 9.5.3以前は、動的ルートのプリフェッチに使用されていました。
  • options - 以下の許可されたフィールドを持つオプションオブジェクト
    • locale - 現在のアクティブなロケールとは異なるロケールを指定できます。falseの場合、urlにはロケールを含める必要があります。アクティブなロケールは使用されません。

ログインページがあり、ログイン後にユーザーをダッシュボードにリダイレクトするとします。その場合、以下の例のようにダッシュボードをプリフェッチして、より高速な遷移を実現できます。

import { useCallback, useEffect } from 'react'
import { useRouter } from 'next/router'
 
export default function Login() {
  const router = useRouter()
  const handleSubmit = useCallback((e) => {
    e.preventDefault()
 
    fetch('/api/login', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        /* Form data */
      }),
    }).then((res) => {
      // Do a fast client-side transition to the already prefetched dashboard page
      if (res.ok) router.push('/dashboard')
    })
  }, [])
 
  useEffect(() => {
    // Prefetch the dashboard page
    router.prefetch('/dashboard')
  }, [router])
 
  return (
    <form onSubmit={handleSubmit}>
      {/* Form fields */}
      <button type="submit">Login</button>
    </form>
  )
}

router.beforePopState

場合によっては(例えば、カスタムサーバーを使用している場合など)、popstateをリッスンし、ルーターがそれに対応する前になにかを実行したい場合があります。

router.beforePopState(cb)
  • cb - 入ってくるpopstateイベントで実行される関数。この関数は、以下のプロパティを持つオブジェクトとしてイベントの状態を受け取ります。
    • url: String - 新しい状態のルート。通常はpageの名前です。
    • as: String - ブラウザに表示されるURL
    • options: Object - router.pushによって送信される追加オプション

cbfalseを返すと、Next.jsルーターはpopstateを処理せず、その場合はあなたがそれを処理する責任を負います。ファイルシステムルーティングの無効化を参照してください。

beforePopStateを使用してリクエストを操作したり、SSRの更新を強制したりすることができます。以下の例を参照してください。

import { useEffect } from 'react'
import { useRouter } from 'next/router'
 
export default function Page() {
  const router = useRouter()
 
  useEffect(() => {
    router.beforePopState(({ url, as, options }) => {
      // I only want to allow these two routes!
      if (as !== '/' && as !== '/other') {
        // Have SSR render bad routes as a 404.
        window.location.href = as
        return false
      }
 
      return true
    })
  }, [router])
 
  return <p>Welcome to the page</p>
}

router.back

履歴を戻ります。ブラウザの戻るボタンをクリックするのと同等です。window.history.back()を実行します。

import { useRouter } from 'next/router'
 
export default function Page() {
  const router = useRouter()
 
  return (
    <button type="button" onClick={() => router.back()}>
      Click here to go back
    </button>
  )
}

router.reload

現在のURLをリロードします。ブラウザの更新ボタンをクリックするのと同等です。window.location.reload()を実行します。

import { useRouter } from 'next/router'
 
export default function Page() {
  const router = useRouter()
 
  return (
    <button type="button" onClick={() => router.reload()}>
      Click here to reload
    </button>
  )
}

router.events

Next.jsルーター内で発生するさまざまなイベントをリッスンできます。サポートされているイベントのリストは以下のとおりです。

  • routeChangeStart(url, { shallow }) - ルートの変更が開始されたときに発火します。
  • routeChangeComplete(url, { shallow }) - ルートの変更が完全に完了したときに発火します。
  • routeChangeError(err, url, { shallow }) - ルート変更時にエラーが発生した場合、またはルートの読み込みがキャンセルされた場合に発火します。
    • err.cancelled - ナビゲーションがキャンセルされたかどうかを示します。
  • beforeHistoryChange(url, { shallow }) - ブラウザの履歴を変更する前に発火します。
  • hashChangeStart(url, { shallow }) - ハッシュが変更されるがページは変更されない場合に発火します。
  • hashChangeComplete(url, { shallow }) - ハッシュが変更されたがページは変更されない場合に発火します。

知っておくと良いこと: ここでいうurlは、basePathを含め、ブラウザに表示されるURLです。

例えば、ルーターイベントrouteChangeStartをリッスンするには、pages/_app.jsを開くか作成し、以下のようにイベントを購読します。

import { useEffect } from 'react'
import { useRouter } from 'next/router'
 
export default function MyApp({ Component, pageProps }) {
  const router = useRouter()
 
  useEffect(() => {
    const handleRouteChange = (url, { shallow }) => {
      console.log(
        `App is changing to ${url} ${
          shallow ? 'with' : 'without'
        } shallow routing`
      )
    }
 
    router.events.on('routeChangeStart', handleRouteChange)
 
    // If the component is unmounted, unsubscribe
    // from the event with the `off` method:
    return () => {
      router.events.off('routeChangeStart', handleRouteChange)
    }
  }, [router])
 
  return <Component {...pageProps} />
}

この例では、ページナビゲーション時にアンマウントされないため、カスタムApp (pages/_app.js) を使用してイベントを購読していますが、アプリケーションのどのコンポーネントでもルーターイベントを購読できます。

ルーターイベントは、コンポーネントがマウントされたとき(useEffectまたはcomponentDidMount / componentWillUnmount)またはイベント発生時に命令的に登録する必要があります。

ルートの読み込みがキャンセルされた場合(例えば、2つのリンクを素早く続けてクリックした場合など)、routeChangeErrorが発火します。そして渡されるerrには、以下の例のようにcancelledプロパティがtrueに設定された状態で含まれます。

import { useEffect } from 'react'
import { useRouter } from 'next/router'
 
export default function MyApp({ Component, pageProps }) {
  const router = useRouter()
 
  useEffect(() => {
    const handleRouteChangeError = (err, url) => {
      if (err.cancelled) {
        console.log(`Route to ${url} was cancelled!`)
      }
    }
 
    router.events.on('routeChangeError', handleRouteChangeError)
 
    // If the component is unmounted, unsubscribe
    // from the event with the `off` method:
    return () => {
      router.events.off('routeChangeError', handleRouteChangeError)
    }
  }, [router])
 
  return <Component {...pageProps} />
}

next/compat/routerエクスポート

これは同じuseRouterフックですが、appディレクトリとpagesディレクトリの両方で使用できます。

next/routerとは異なり、ページルーターがマウントされていない場合にエラーをスローせず、代わりにNextRouter | nullの戻り値の型を持ちます。これにより、開発者はコンポーネントをappルーターに移行する際に、apppagesの両方で動作するように変換できます。

以前はこのようなコンポーネントでしたが

import { useRouter } from 'next/router'
const MyComponent = () => {
  const { isReady, query } = useRouter()
  // ...
}

next/compat/routerに変換すると、nullを分割代入できないためエラーが発生します。代わりに、開発者は新しいフックを活用できるようになります。

import { useEffect } from 'react'
import { useRouter } from 'next/compat/router'
import { useSearchParams } from 'next/navigation'
const MyComponent = () => {
  const router = useRouter() // may be null or a NextRouter instance
  const searchParams = useSearchParams()
  useEffect(() => {
    if (router && !router.isReady) {
      return
    }
    // In `app/`, searchParams will be ready immediately with the values, in
    // `pages/` it will be available after the router is ready.
    const search = searchParams.get('search')
    // ...
  }, [router, searchParams])
  // ...
}

このコンポーネントは、pagesappの両方のディレクトリで動作するようになります。コンポーネントがpagesで使用されなくなったら、compatルーターへの参照を削除できます。

import { useSearchParams } from 'next/navigation'
const MyComponent = () => {
  const searchParams = useSearchParams()
  // As this component is only used in `app/`, the compat router can be removed.
  const search = searchParams.get('search')
  // ...
}

pagesでNext.jsコンテキスト外でuseRouterを使用する

もう1つの特定のユースケースは、pagesディレクトリのgetServerSideProps内など、Next.jsアプリケーションコンテキスト外でコンポーネントをレンダリングする場合です。この場合、互換ルーターを使用してエラーを回避できます。

import { renderToString } from 'react-dom/server'
import { useRouter } from 'next/compat/router'
const MyComponent = () => {
  const router = useRouter() // may be null or a NextRouter instance
  // ...
}
export async function getServerSideProps() {
  const renderedComponent = renderToString(<MyComponent />)
  return {
    props: {
      renderedComponent,
    },
  }
}

潜在的なESLintエラー

routerオブジェクトでアクセス可能な特定のメソッドはPromiseを返します。ESLintルールno-floating-promisesを有効にしている場合、グローバルまたは影響を受ける行で無効にすることを検討してください。

アプリケーションがこのルールを必要とする場合、Promiseをvoidにするか、async関数を使用し、Promiseをawaitしてから関数呼び出しをvoidにする必要があります。この方法は、メソッドがonClickハンドラ内から呼び出される場合には適用できません

影響を受けるメソッドは次のとおりです。

  • router.push
  • router.replace
  • router.prefetch

潜在的な解決策

import { useEffect } from 'react'
import { useRouter } from 'next/router'
 
// Here you would fetch and return the user
const useUser = () => ({ user: null, loading: false })
 
export default function Page() {
  const { user, loading } = useUser()
  const router = useRouter()
 
  useEffect(() => {
    // disable the linting on the next line - This is the cleanest solution
    // eslint-disable-next-line no-floating-promises
    router.push('/login')
 
    // void the Promise returned by router.push
    if (!(user || loading)) {
      void router.push('/login')
    }
    // or use an async function, await the Promise, then void the function call
    async function handleRouteChange() {
      if (!(user || loading)) {
        await router.push('/login')
      }
    }
    void handleRouteChange()
  }, [user, loading])
 
  return <p>Redirecting...</p>
}

withRouter

useRouterが最適でない場合、withRouterを使用すると、同じrouterオブジェクトを任意のコンポーネントに追加できます。

使用方法

import { withRouter } from 'next/router'
 
function Page({ router }) {
  return <p>{router.pathname}</p>
}
 
export default withRouter(Page)

TypeScript

withRouterでクラスコンポーネントを使用するには、コンポーネントがrouterプロップを受け入れる必要があります。

import React from 'react'
import { withRouter, NextRouter } from 'next/router'
 
interface WithRouterProps {
  router: NextRouter
}
 
interface MyComponentProps extends WithRouterProps {}
 
class MyComponent extends React.Component<MyComponentProps> {
  render() {
    return <p>{this.props.router.pathname}</p>
  }
}
 
export default withRouter(MyComponent)