1
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】useRouterのonInvalidateの使い方

Posted at

onInvalidateとは

onInvalidaterouter.prefetch()の第2引数として渡すコールバック関数で、プリフェッチされたデータがNext.jsによって「古い」と判断されたときに呼び出されます。

重要な特性:

  • プリフェッチリクエストごとに最大1回のみ呼び出される
  • キャッシュの無効化を検知し、新しいプリフェッチをトリガーするタイミングを知らせる

onInvalidateを使用して、キャッシュが無効化されるたびに自動的に再プリフェッチするリンクは以下のように実装できます。

'use client'
import { useRouter } from 'next/navigation'
import { useEffect } from 'react'

function ManualPrefetchLink({
  href,
  children,
}: {
  href: string
  children: React.ReactNode
}) {
  const router = useRouter()

  useEffect(() => {
    let cancelled = false

    const poll = () => {
      if (!cancelled) {
        router.prefetch(href, { onInvalidate: poll })
      }
    }

    poll() // 初回プリフェッチを実行

    return () => {
      cancelled = true // クリーンアップ
    }
  }, [href, router])

  return (
    <a
      href={href}
      onClick={(event) => {
        event.preventDefault()
        router.push(href)
      }}
    >
      {children}
    </a>
  )
}

参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?