Last active
June 21, 2024 15:06
-
-
Save typeofweb/6fc7290f5a531ad54fafab768167183b to your computer and use it in GitHub Desktop.
Link with on-hover prefetching in Next.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// See https://typeofweb.hashnode.dev/nextjs-prefetch-onmouseenter for a detailed explanation and more code | |
// See it in action: https://demo.yournextstore.com | |
"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(); | |
return ( | |
<Link | |
{...props} | |
onMouseEnter={(e) => { | |
const href = typeof props.href === "string" ? props.href : props.href.href; | |
if (href) { | |
router.prefetch(href); | |
} | |
return props.onMouseEnter?.(e); | |
}} | |
/> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment