0
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入門】router.push と router.replace の違い

Last updated at Posted at 2025-10-30

初めに

Next.jsでページ遷移するときにuseRouter()を使って実装すると思いますが、pushreplaceの違いがわかっていなかったので整理します。

router.pushとは

  • 現在のURL履歴に新しい履歴を追加してページを移動する
  • 「戻るボタン」で前のページに戻れる
import { useRouter } from 'next/router'

export default function Home() {
  const router = useRouter()

  const handleClick = () => {
    router.push('/profile')
  }

  return <button onClick={handleClick}>プロフィールへ</button>
}

たとえば /home → /profile と移動すると、ブラウザの戻るボタンで /home に戻ることができる

履歴: [ /home ] → [ /profile ]

router.replaceとは

  • 現在のページの履歴を上書きする
  • そのため、前のページの履歴がブラウザから消える
  • 結果として、「戻るボタン」を押しても前のページには戻れない
  • 主にログイン後やフォーム送信後など、前の画面に戻らせたくないときに使う
import { useRouter } from 'next/router'

export default function Login() {
  const router = useRouter()

  const handleLogin = () => {
    // 認証後にマイページへ遷移
    router.replace('/mypage')
  }

  return <button onClick={handleLogin}>ログイン</button>
}

たとえば /login ページから router.replace('/mypage') を実行すると、/login の履歴が消える

履歴: [ /mypage ]
0
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
0
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?