useForesight
This is a React hook that integrates with js.foresight to predict user interactions based on mouse trajectory, keyboard navigation, and scroll behavior. It enables proactive prefetching and UI optimization before users actually interact with elements.
The useForesight hook integrates with the
js.foresight library to provide predictive
interaction detection. This allows you to trigger callbacks before users
actually click or interact with elements, enabling smart prefetching
strategies.
import { useForesight } from '@suspensive/react-dom'
import { usePrefetchQuery } from '@suspensive/react-query'
const PostCard = ({ post }: { post: Post }) => {
const prefetchComments = usePrefetchQuery({
queryKey: ['posts', post.id, 'comments'],
queryFn: () => getPostComments(post.id),
})
const { ref } = useForesight({
callback: () => {
// This will be called when user is likely to interact with the element
prefetchComments()
},
name: `post-${post.id}`,
hitSlop: 10,
})
return (
<div ref={ref}>
<h2>{post.title}</h2>
<p>{post.description}</p>
<Link to={`/posts/${post.id}/comments`}>See comments</Link>
</div>
)
}Basic Usage
The hook returns a ref function and registration information that you can use to track interaction predictions.
options.callback
The callback function is called when the user is predicted to interact with the element.
options.hitSlop
hitSlop expands the interaction detection area around the element.
options.disabled
Use disabled to conditionally enable/disable foresight tracking.
options.autoInitialize
Control whether to automatically initialize the ForesightManager.
Return Value
The hook returns an object with the following properties:
ref: A ref function to attach to the target elementregisterResult: Information about the registration result (includesisTouchDevice,isLimitedConnection, etc.)isRegistered: Boolean indicating whether the element is currently registered with ForesightManager