Next用hash取得custom hook
常に最新のhashを返すcustom hook。
code:tsx
import { useRouter } from 'next/router'
import { useCallback, useEffect, useState } from 'react'
export const useHash = () => {
typeof location === 'undefined' ? '' : location.hash
)
const router = useRouter()
const handleHashChanged = useCallback(() => {
setHash(typeof location === 'undefined' ? '' : location.hash)
}, [])
useEffect(() => {
router.events.on('hashChangeComplete', handleHashChanged)
return () => {
router.events.off('hashChangeComplete', handleHashChanged)
}
return hash
}
router eventsには
- hashChangeStart(変更前)
- hashChangeComplete(変更後)
の2つのタイミングがある。
routerChangeStart、Completeもある。