import Link from 'next/link' import { ComponentProps, forwardRef, useRef } from 'react' type LinkProps = ComponentProps export interface PrefetchableLinkProps extends Omit { prefetcher: () => void } const DELAY = 75 const PrefetchableLink = forwardRef( function PrefetchableLink({ prefetcher, children, ...props }, ref) { const mouseOverStartRef = useRef(null) const prefetchTimeoutRef = useRef(null) function onPrefetch() { const now = Date.now() // setTimeout is not guaranteed to be precise, so we need to check the time again if (mouseOverStartRef.current && now - mouseOverStartRef.current >= DELAY) { prefetcher() } } function onMouseEnter() { mouseOverStartRef.current = Date.now() prefetchTimeoutRef.current = window.setTimeout(onPrefetch, DELAY) } function onMouseLeave() { mouseOverStartRef.current = null if (prefetchTimeoutRef.current) { clearTimeout(prefetchTimeoutRef.current) prefetchTimeoutRef.current = null } } return ( {children} ) } ) export default PrefetchableLink