LoginSignup
1
0

Next.jsでの履歴スタック利用

Posted at

履歴スタックとは

Webブラウザ上での閲覧履歴は、スタックとして管理されている。それを履歴スタックという。
例えば、以下のような履歴スタックがあるとする。

履歴1 履歴2 履歴3
現在位置

履歴3から戻るボタンを押して履歴2に戻ったことを想定。
ここから先に進むボタンを押すと

履歴1 履歴2 履歴3
現在位置

当然こうなる。もう一度戻るボタンを押そう。

履歴1 履歴2 履歴3
現在位置

ここで、履歴2のページ内で、別のaタグのリンクをクリックしてみる。そうすると...

履歴1 履歴2 履歴4
現在位置

履歴3がpopされ履歴4が現在位置となる。こうなると、戻る/進むボタンを押しても履歴3には当然戻れない。

Next.jsでJavascriptのHistory API利用

Next.jsではjavascriptのネイティブなHistoryAPIを利用して、リロード無しでブラウザの履歴とURLを動作することができる。
主にユーザー体験を向上させるために利用することができる。

メリット
・リロードによる待機時間を減らせる
・ブックマークやURL共有時に状態を共有できる
・履歴の細かな制御ができるため開発を柔軟にできる

公式より引用

Using the native History API
Next.js allows you to use the native window.history.pushState and window.history.replaceState methods to update the browser's history stack without reloading the page.

pushState and replaceState calls integrate into the Next.js Router, allowing you to sync with usePathname and useSearchParams.

window.history.pushState
Use it to add a new entry to the browser's history stack. The user can navigate back to the previous state. For example, to sort a list of products:

'use client'
 
import { useSearchParams } from 'next/navigation'
 
export default function SortProducts() {
  const searchParams = useSearchParams()
 
  function updateSorting(sortOrder: string) {
    const params = new URLSearchParams(searchParams.toString())
    params.set('sort', sortOrder)
    window.history.pushState(null, '', `?${params.toString()}`)
  }
 
  return (
    <>
      <button onClick={() => updateSorting('asc')}>Sort Ascending</button>
      <button onClick={() => updateSorting('desc')}>Sort Descending</button>
    </>
  )
}

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