Skip to main content
Version: 4.x

React Router

React Router's Prefetching​

This example requires React Router v7 in Framework Mode. Its Link supports prefetch="intent" and prefetch="viewport", and PrefetchPageLinks can prefetch a route when ForesightJS predicts intent.

prefetch="intent" starts when the link is hovered or focused, and prefetch="viewport" prefetches every visible link. ForesightJS starts earlier than intent by predicting the target from mouse trajectory and Tab navigation, and only prefetches links the user is likely to click.

PrefetchPageLinks requires framework context and cannot be used under a plain BrowserRouter or standalone RouterProvider. In those apps, put your own data fetch or route-module import in the Foresight callback instead.

Below is a wrapper around the React Router Link that prefetches with ForesightJS using the useForesight hook. The callback flips a flag that renders PrefetchPageLinks for the target route. On mobile devices ForesightJS falls back to the configured touchDeviceStrategy.

import { useForesight, type ForesightRegisterOptionsWithoutElement } from "@foresightjs/react"
import { useState } from "react"
import { createPath, Link, PrefetchPageLinks, useResolvedPath, type LinkProps } from "react-router"

interface ForesightLinkProps
extends Omit<LinkProps, "prefetch">, Omit<ForesightRegisterOptionsWithoutElement, "callback"> {
children: React.ReactNode
className?: string
}

export function ForesightLink({
children,
className,
hitSlop,
name,
meta,
reactivateAfter,
enabled,
...props
}: ForesightLinkProps) {
const [shouldPrefetch, setShouldPrefetch] = useState(false)
const page = createPath(useResolvedPath(props.to, { relative: props.relative }))
const { elementRef } = useForesight<HTMLAnchorElement>({
callback: () => setShouldPrefetch(true),
hitSlop,
name,
meta,
reactivateAfter,
enabled,
})

return (
<>
{shouldPrefetch && <PrefetchPageLinks page={page} />}
<Link {...props} ref={elementRef} prefetch="none" className={className}>
{children}
</Link>
</>
)
}
export function Navigation() {
return (
<>
<ForesightLink to={"/contact"} hitSlop={20} name="contact-link">
contact
</ForesightLink>
<ForesightLink to={"/about"} name="about-link">
about
</ForesightLink>
</>
)
}