Prefetch on MouseDown in Nextjs 15 App Router
Unanswered
Japanese cockle posted this in #help-forum
Japanese cockleOP
Hey, I had the below code before for setting up my own version of Link that would make it so only prefetch happened on mousedown. But, this didn't work... I am not sure why. I went to a page where it was used as a link and it still made it so that when it entered on viewport nextjs would load it. Has anyone made a version of Link that just works with mouse hover or on mousedown like I am trying to do?
'use client'
import Link from 'next/link'
import { useRouter } from 'next/navigation'
import { type ComponentPropsWithRef } from 'react'
export const SuperLink = (props: ComponentPropsWithRef<typeof Link>) => {
const router = useRouter()
const strHref = typeof props.href === 'string' ? props.href : props.href.href
const conditionalPrefetch = () => {
if (strHref) {
void router.prefetch(strHref)
}
}
return (
<Link
{...props}
prefetch={false}
onMouseDown={(e) => {
conditionalPrefetch()
return props.onMouseDown?.(e)
}}
onTouchStart={(e) => {
conditionalPrefetch()
return props.onTouchStart?.(e)
}}
//INFO: Don't want this on if someone is just flipping through multiple links focusing
// onFocus={(e) => {
// conditionalPrefetch()
// return props.onFocus?.(e)
// }}
/>
)
}