Quick Start
Register your first element with ForesightJS in React and see how prediction works.
Basic Usage Example
In React you register an element with the useForesight hook. Give it a callback and attach the returned elementRef to the element you want to track:
import { useForesight } from "@foresightjs/react"
function PrefetchButton() {
const { elementRef } = useForesight<HTMLButtonElement>({
callback: () => console.log("prefetch logic here"),
})
return <button ref={elementRef}>Prefetch</button>
}
That's it!
Unregistration is automatic
The hook registers the element when it mounts and unregisters it when the component unmounts, so you never have to call unregister() yourself.
Provide registration options
For finer control, pass any of these options:
import { useForesight } from "@foresightjs/react"
function PrefetchButton() {
const { elementRef } = useForesight<HTMLButtonElement>({
callback: () => console.log("prefetch logic here"),
hitSlop: 50, // slop around the element, making its hitbox bigger
name: "My Foresight button!", // name visible in the debug tools
meta: {
route: "/about",
}, // your custom meta data for analytics
reactivateAfter: 5 * 60 * 1000, // time for the element to reactivate after the callback has been hit
})
return <button ref={elementRef}>Prefetch</button>
}
See registration options for the full list. The hook also returns the element's reactive prediction state (isPredicted, isActive, …); read about it in useForesight.
Development Tools
ForesightJS has dedicated Development Tools that help you understand and tune how prediction is working in your application:
pnpm add js.foresight-devtools
# or
npm install js.foresight-devtools
# or
yarn add js.foresight-devtools
import { ForesightDevtools } from "js.foresight-devtools"
// Initialize development tools
ForesightDevtools.initialize({
// optional props
})